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

后端 未结 5 1537
梦谈多话
梦谈多话 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:55

    You should use FULL OUTER JOIN.

    DECLARE @table1 TABLE(
        [name] char(1)
    )
    DECLARE @table2 TABLE(
        [name] char(1)
    )
    INSERT INTO @table1 VALUES ('A'),('B'),('C'),('D'),('E'),('F'),('G')
    INSERT INTO @table2 VALUES ('A'),('B'),('Q'),('C'),('D'),('F'),('G')
    SELECT 
        IIF(T1.name IS NULL,T2.name,T1.name) as 'Name',
        CASE WHEN T1.name IS NULL THEN 'newly added' WHEN T2.name IS NULL THEN 'removed' ELSE '' END as 'Status'
    FROM @table1 T1
    FULL OUTER JOIN @table2 T2 ON T1.name = T2.name
    

    There ise one more possible method:

    DECLARE @table1 TABLE(
        [name] char(1)
    )
    DECLARE @table2 TABLE(
        [name] char(1)
    )
    INSERT INTO @table1 VALUES ('A'),('B'),('C'),('D'),('E'),('F'),('G')
    INSERT INTO @table2 VALUES ('A'),('B'),('Q'),('C'),('D'),('F'),('G')
    SELECT 
        T1.name as 'Full_List',
        IIF(T2.name IS NOT NULL,'','removed') as 'Status'
    FROM @table1 T1 
    LEFT OUTER JOIN @table2 T2 ON T1.name = T2.name
    UNION ALL
    SELECT 
        T2.name,
        IIF(T1.name IS NULL,'Added','') 
    
    FROM @table2 T2 
    LEFT OUTER JOIN @table1 T1 ON T1.name = T2.name
    WHERE T1.name IS NULL
    
    
    

提交回复
热议问题