Insert Into With Exists

  •  

    I would like to insert rows into tableX from TableY where they already do not exist in tableX.

    In essenece every week all rows are added to TableX for certain processing from table Y. However

    occasionally, some rows may be added to the tableY after they have been copied to TableX and processed

    there. I would like to get this delta from TableY. Consider that I do not want to add any flags to

    either table, but would like a SQL insert statement to resolve this. The following code generates

    syntax error and the BOL does not have any example for this structure either.

    Insert into TableX

    Select Col1, Col2

    From TableY

    And Not Exists (Select * From TableX x2 Where Tablex.Col1 = x2.Col1 and Tablex.Col2 = x2.Col2)

  • You could use...

    INSERT INTO TableX

    SELECT Col1, Col2

    FROM TableY

    WHERE Col1+Col2 NOT IN (SELECT Col1+Col2 FROM TableX)



    Shamless self promotion - read my blog http://sirsql.net

  • You need this :

    Insert into TableX

    Select Y.Col1, Y.Col2

    From TableY Y

    where Not Exists (Select 1 From TableX X  Where X.Col1 = Y.Col1 and X.Col2 = Y.Col2)

  • Or, without using exists :

    insert x

    select y.col1, y.col2

    from tabley as y

    left join tablex as x on x.col1 = y.col1 and x.col2 = y.col2

    where x.col1 is null

  • Thanks. All of them just work fine.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply