Check if the value from one table exists in another tables in SQL Server I have one table (tbl1) with column ID, the values can be duplicated. I have others tables (tbl2, tbl3...) with column ID , values are unique.
I want to write a trigger on insert row in tbl1 and check if ID in new row has not exists in tbl2,tbl3.... There is part of my code. 

    CREATE TRIGGER dbo.tbl1_ID
       ON dbo.tbl1
       AFTER INSERT
    AS
    BEGIN

       SET NOCOUNT ON;
       DECLARE @CHECK int

       SELECT OBJECTID,ID, ROW_NUMBER() over(Order by OBJECTID) as aID into #T1 
       from inserted where (ID is not null)

       SELECT @CHECK = COUNT(p.ID from #T1 as p where not exists (select e.ID 
                                                                  from dbo.tbl2 as e 
                                                                  where p.ID=e.ID))

       IF @CHECK&gt;0
           BEGIN
                RAISERROR("ID ALREADY EXISTS",16,1);
                ROLLBACK TRANSACTION;
           END
    END


I don't know how to check in a range of tables, they are stored in table JoinTables(f.ex.). I suppose I need function here.

Table JoinTables similar to

obID|firsttable|secondtable

 1  |   tbl1   |   tbl2 
 2  |   tbl1   |   tbl3
 3  |   tbl1   |   tbl4
 4  |   tblM   |   tbl5
 5  |   tblM   |   tbl6
I think you could get it with a single statement.

CREATE TRIGGER t1_insert ON T1
AFTER INSERT
AS
BEGIN

    IF EXISTS(SELECT 
                  1
              FROM
                  inserted
              JOIN
                  (
                   SELECT ID FROM T2
                   UNION ALL
                   SELECT ID FROM T3
                   UNION ALL
                   SELECT ID FROM T4
                  ) others
                  ON others.ID = inserted.ID)
    BEGIN
        PRINT 'YES';
    END
    ELSE
    BEGIN
        PRINT 'NO';
    END

END


db&lt;>fiddle here