Compare two tables and insert all records with added or removed status in 3rd table using SQL Server procedure

后端 未结 5 1592
梦谈多话
梦谈多话 2021-01-27 17:43

I have table A and table B . I have to compare this tables records and insert data to table C using SQL Server procedure in below format

table A

  name
          


        
5条回答
  •  花落未央
    2021-01-27 17:59

    please try with below query (SQL FIDDLE):

    CREATE PROCEDURE update_records
    AS
    BEGIN
        INSERT INTO C(name, status)
        SELECT AB.name, AB.status FROM(
        SELECT (case when A.name is null then B.name else A.name end) as name,
           (CASE 
            WHEN A.name is null THEN 'newly added'
            WHEN B.name is null THEN 'removed'
         END) AS status
        FROM A
        FULL JOIN B on B.name = A.name
      ) as AB
      ORDER by AB.name
    
    END
    

提交回复
热议问题