使用SQL中的允许空值检查两个表之间的差异

时间:2013-07-31 23:47:39

标签: sql sql-server sql-server-2008 tsql sql-update

我有两个不同的表,Table1&表2每个都有自己的值集。我想检查一列,看看彼此之间是否存在任何差异,并相应地UPDATE表1。我有这个查询更新每一行,无论它们在我检查的值是否有所不同:

UPDATE Table1
SET value = t2.value
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.ID = t2.ID

我尝试使用WHERE t1.value <> t2.value,但由于t1t2都可以为空,因此该功能无法正常运行。我想要一个只检查和更新其值t1t2不同的查询。

4 个答案:

答案 0 :(得分:2)

...
WHERE t1.value <> t2.value
OR (t1.value IS NULL AND t2.value IS NOT NULL)
OR (t1.value IS NOT NULL AND t2.value IS NULL);

答案 1 :(得分:1)

您可以点击where t1.id is not null and t2.ID is not null

例如:

UPDATE Table1
SET value = t2.value
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.ID = t2.ID
WHERE t1.value <> t2.value
AND t1.id is not null 
AND t2.ID is not null

答案 2 :(得分:1)

如果我正确理解了这个问题,您可以在where子句中列出要进行更新的条件:

UPDATE Table1
    SET value = t2.value
    FROM Table1 t1 INNER JOIN
         Table2 t2
         ON t1.ID = t2.ID
   WHERE (table1.value <> t2.value) or
         (table1.value is null and table2.value is not null) or
         (table1.value is not null and table2.value is null)

答案 3 :(得分:0)

如何使用coalesce为空值提供默认值?像这样改变你的where子句。

WHERE COALESCE(t1.value,'') <> COALESCE(t2.value,'')