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
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