I have a two tables with same column names. I would like to compare two columns . For eg:- Table 1 has server and IP address like
Server1 ip1 comp1 192.168.1.1 comp2 192.168.1.32
Table 2:-
Server2 ip2 comp3 192.168.1.1 comp2 192.168.1.33 comp4 192.168.1.42 comp5 192.168.1.43
Desired output:-
server1 ip1 server2 ip2 iserverchange isipchange comp1 192.168.1.1 comp3 192.168.1.1 Yes No comp2 192.168.1.32 comp2 192.168.1.33 No Yes null null comp5 192.168.1.43 No No null null comp4 192.168.1.42 No No
Advertisement
Answer
It looks like a FULL JOIN
is what you need here.
Sample data
DECLARE @T1 TABLE (Server1 varchar(50), ip1 varchar(50)); DECLARE @T2 TABLE (Server2 varchar(50), ip2 varchar(50)); INSERT INTO @T1 VALUES ('comp1', '192.168.1.1'), ('comp2', '192.168.1.32'); INSERT INTO @T2 VALUES ('comp3', '192.168.1.1'), ('comp2', '192.168.1.33'), ('comp4', '192.168.1.42'), ('comp5', '192.168.1.43');
Query
SELECT T1.Server1 ,T1.ip1 ,T2.Server2 ,T2.ip2 ,CASE WHEN T1.Server1 <> T2.Server2 THEN 'Yes' ELSE 'No' END AS iserverchange ,CASE WHEN T1.ip1 <> T2.ip2 THEN 'Yes' ELSE 'No' END AS isipchange FROM @T1 AS T1 FULL JOIN @T2 AS T2 ON T1.Server1 = T2.Server2 OR T1.ip1 = T2.ip2 ;
Result
| Server1 | ip1 | Server2 | ip2 | iserverchange | isipchange | |---------|--------------|---------|--------------|---------------|------------| | comp1 | 192.168.1.1 | comp3 | 192.168.1.1 | Yes | No | | comp2 | 192.168.1.32 | comp2 | 192.168.1.33 | No | Yes | | NULL | NULL | comp4 | 192.168.1.42 | No | No | | NULL | NULL | comp5 | 192.168.1.43 | No | No |