Search code examples
sqlsql-serversql-server-2008t-sql

SQL: Insert from first table into second table when records not exist in second table


I have two table with same column but the second table has one column more than first table(InfoDate).

Table 1

KID       ParentID         KLevel
----------------------------------------
1            0                 1
2            1                 2
3            1                 2

Table 2

KID ParentID    KLevel      InfoDate
------------------------------------------------------------    
2   1            2          2015-12-31 00:00:00.000

I want insert all record from first table to second table that not exist in second table with condition InfoDate=2015-12-31 00:00:00.000

For example, in this sample example records with KID=1 and KID=3 must be inserted into table 2.

I do:

insert into table2 (KID , ParentID , KLevel)
select KID , ParentID , KLevel from table1
where not EXISTS(
    SELECT KID , ParentID , KLevel FROM table2 WHERE InfoDate = '2015-12-31 00:00:00.000'
);

but (0 row(s) affected)

could you help me, please?


Solution

  • Your WHERE NOT EXISTS... condition does not really make sense. Right now you're only checking, if there is no row with InfoDate = '2015-12-31 00:00:00.000'. Since there obviously is such a row, no records are affected.

    Try this:

    INSERT INTO [table2] (
           [KID]
         , [ParentID]
         , [KLevel]) 
    SELECT
          [KID]
        , [ParentID]
        , [KLevel]
    FROM [table1]
    WHERE NOT EXISTS (
        SELECT
            [KID]
            , [ParentID]
            , [KLevel]
        FROM [table2]
        WHERE [InfoDate] = '2015-12-31 00:00:00.000'
          AND [table1].[KID] = [table2].[KID]
          AND [table1].[ParentID] = [table2].[ParentID]
          AND [table1].[KLevel] = [table2].[KLevel])