0

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.

4

2 回答 2

2
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 
于 2013-01-21T15:30:49.340 回答
2

假设您认为NULL是相同的(而 SQL Server 没有):

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;
于 2013-01-21T15:25:24.973 回答