两个表不匹配列值

时间:2012-08-27 17:58:15

标签: c# sql-server

我有两个表Say Table1(ID,Name,Description)和Table2(ID,Name,Description)。

我需要找出Table1中Table2不存在的那些记录,如果记录存在则会比较其名称和描述,并显示哪些列不匹配。 ID是用于比较的字段。

例如

Table 1
( 1, Jon,Student) 

Table 2 
(1,Jon, Teacher) 

因此查询应返回Description mismatch

2 个答案:

答案 0 :(得分:0)

您可以使用SELECT

解决它
SELECT  TABLE1.ID,  CASE WHEN TABLE1.NAME <> TABLE2.NAME THEN 'NAME different' 
                         ELSE 'NAME equal'
                    END
                  , TABLE1.NAME, TABLE2.NAME
                  , CASE WHEN TABLE1.DESCRIPTION <> TABLE2.DESCRIPTION THEN 'DESCRIPTION different' 
                         ELSE 'DESCRIPTION equal'
                    END
                  , TABLE1.DESCRIPTION, TABLE2.DESCRIPTION
  FROM  TABLE1, TABLE2
 WHERE   TABLE1.ID = TABLE2.ID  

如果您只想要不同的联合行添加到are子句

AND (TABLE1.NAME <> TABLE2.NAME OR TABLE1.DESCRIPTION <> TABLE2.DESCRIPTION)

如果其他表中可能没有ID,则必须使用左连接

SELECT      TABLE1.ID,  
            CASE WHEN TABLE2.ID IS NULL THEN 'No corresponding row in TABLE2' END
            CASE WHEN TABLE1.NAME <> TABLE2.NAME THEN 'NAME different' ELSE 'NAME equal' END,           
            TABLE1.NAME, TABLE2.NAME
            CASE WHEN TABLE1.DESCRIPTION <> TABLE2.DESCRIPTION THEN 'DESCRIPTION different' ELSE 'DESCRIPTION equal' END,
            TABLE1.DESCRIPTION, TABLE2.DESCRIPTION
       FROM TABLE1
  LEFT JOIN TABLE2 ON TABLE1.ID = TABLE2.ID  

答案 1 :(得分:0)

你在找这样的东西吗?

SELECT
t1.id,
CASE
WHEN t2.id IS NULL THEN 'does not exist in table2'
WHEN t1.Name != t2.Name AND t1.Description = t2.Description THEN 'Name is different'
WHEN t1.Name = t2.Name AND t1.Description != t2.Description THEN 'Description is different'
ELSE 'Both Name and Description differ'
END AS what_is_the_difference
FROM
table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id