SQL Server中的EXCEPT SQL语句未返回预期结果

时间:2016-11-25 22:54:12

标签: sql sql-server tsql

我有两个相同但位于不同服务器上的表。一张表缺少我验证过的一行。我试图比较这些表来找到丢失的记录

通过

SELECT  GUID FROM dbo.tableA
EXCEPT 
SELECT  GUID FROM [Server2].MyDatabase.dbo.tableA

或其他方式

SELECT GUID FROM [Server2].MyDatabase.dbo.tableA
EXCEPT 
SELECT GUID FROM dbo.tableA

两个查询都返回零结果。我在两个表上使用了select count(*)并且计数不同

我做错了什么?

感谢您提前提供任何反馈

4 个答案:

答案 0 :(得分:4)

计数可能不同,except仍然可以返回零行。怎么样?如果一个或两个表中有重复项。

这是一个可以帮助您找到差异的修改:

SELECT GUID, ROW_NUMBER() OVER (PARTITION BY GUID ORDER BY GUID) as seqnum
FROM dbo.tableA
EXCEPT 
SELECT GUID, ROW_NUMBER() OVER (PARTITION BY GUID ORDER BY GUID) as seqnum
FROM [Server2].MyDatabase.dbo.tableA

答案 1 :(得分:0)

根据我的经验,EXCEPT运算符在使用链接服务器时无法正常运行。为什么?我不知道。

作为一种解决方法,我将远程服务器中的行插入到本地临时表中,然后进行比较:(由于其他原因,我还将本地行复制到第二个临时表)

Select GUID
  Into #Server2_tblA
  From [Server2].MyDatabase.dbo.tableA;

Select GUID
  Into #Local_tblA
  From dbo.tableA;

Select GUID From #Server2_tblA
Except
Select GUID From #Local_tblA;
...

答案 2 :(得分:0)

表A值未显示在MyDatabase.dbo.tableA.Using中不存在caluse以获取此结果

SELECT GUID 
FROM dbo.tableA WHERE NOT EXISTS(SELECT 1 
                                 FROM [Server2].MyDatabase.dbo.tableA 
                                 WHERE GUID = [Server2].MyDatabase.dbo.tableA.GUID )

答案 3 :(得分:0)

When you have set it depends on order and it is based on set theory.

  • 2, 3, 4 without (=except) 3 --> set with values 2, 4
  • 3 without 2, 3, 4 --> it means empty set
  • 3, 3, 4 without 1, 2, 3 (it's your case) --> it means set with only one value 4

Except means filter any row from first set, where values are contained in second set. Your queries return the same output, because in your table exist duplicate rows (with the same value).

Please don't use except/intersect - use exists, in or join clauses.