SQL Query

  • Does anyone know the syntax of a query statement that compares two tables and updates either table if a record doesn't exist.

  • I usually do this with two separate queries, one a left join and one a right join.

    Andy

  • Try This. I did it with two tables (tbl_new_1 and tbl_new_2) both containing columns for stock_id VARCHAR(10), description VARCHAR(20). Primary key on stock_id

    INSERT dbo.tbl_new_1(

    stock_id,

    description)

    SELECT

    stock_id,

    description

    FROM dbo.tbl_new_2 a

    WHERE NOT EXISTS (

    SELECT stock_id

    FROM dbo.tbl_new_1 b

    WHERE a.stock_id = b.stock_id)

    The correlated subquey in the EXISTS statment will find those records in one table that don't exist in the other and the INSERT SELECT clause will pop them into the target table.

    Iknow it means two stages, but if you wrap the two queries into a TSQL stored procedure then one simple EXEC call will do the job


    I have found it is possible to please all of the people all of the time if you do exactly what they want. Harold Macmillan 1961

Viewing 3 posts - 1 through 2 (of 2 total)

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