Reputation: 11
I have two databases ABC
and XYZ
with the same table structure, but different data.
I want to compare the values of col1, col2, col3, col4
from tbl_123
from both databases, and return an additional column RESULT
as 1 if values in both tables are same and 0 it they are not.
col1
is the primary key in both tables, and the other columns are nullable.
Upvotes: 0
Views: 1275
Reputation: 453142
SELECT ISNULL(T1.col1, T2.col1) AS col1,
CASE
WHEN NOT EXISTS(SELECT T1.col2,
T1.col3,
T1.col4
EXCEPT
SELECT T2.col2,
T2.col3,
T2.col4) THEN 1
ELSE 0
END AS Result,
T1.col2,
T2.col2,
T1.col3,
T2.col3,
T1.col4,
T2.col4
FROM XYZ.dbo.tbl_123 T1
FULL OUTER JOIN ABC.dbo.tbl_123 T2
ON T1.col1 = T2.col1
Upvotes: 2
Reputation:
Assuming you consider NULL
to be the same (whereas SQL Server does not):
SELECT
d1.col1, d1.col2, d1.col3, d1.col4,
d2.col1, d2.col2, d2.col3, d2.col4,
[RESULT] = CASE
WHEN (d1.col2 = d2.col2 OR (d1.col2 IS NULL AND d2.col2 IS NULL))
AND (d1.col3 = d2.col3 OR (d1.col3 IS NULL AND d2.col3 IS NULL))
AND (d1.col4 = d2.col4 OR (d1.col4 IS NULL AND d2.col4 IS NULL))
THEN 1 ELSE 0 END
FROM ABC.dbo.tbl_123 AS d1
FULL OUTER JOIN
XYZ.dbo.tbl_123 AS d2
ON d1.col1 = d2.col2;
Upvotes: 2