【问题标题】:How to compare two tables without unique identifier in SQL如何在 SQL 中比较没有唯一标识符的两个表
【发布时间】:2026-02-12 00:15:01
【问题描述】:

我有两个具有相同结构但没有唯一标识符的表。如何比较这两个表

我尝试使用行号来比较它们。代码如下

WITH source AS  
(  
     SELECT 
         ROW_NUMBER() OVER(ORDER BY Customer Account    address) AS RowN,   
         Customer Account address
     FROM 
         old
)  

WITH target AS  
(  
     SELECT 
         ROW_NUMBER() OVER(ORDER BY Customer Account    address) AS RowN,   
         Customer Account address
     FROM 
         New
)  

SELECT 
    s.address, t.address 
FROM
    source s
JOIN
    traget t ON s.RowN = t.RowN
WHERE
    s.Customer != t.Customer
    OR s.Account != t.Account
    OR s.address != t.address

结果除外:

s.address   t.address
---------------------
BB1         BB2

但我得到一个错误

关键字“WITH”附近的语法不正确

Microsoft SQL Server 版本:Microsoft SQL Server 2017

【问题讨论】:

  • 去掉第二个WITH,开始定义CTE的时候只需要1个,然后用逗号分隔(也没有)。
  • 如果你ORDER BY 是一个列的列表,你也需要用逗号分隔它们
  • Customer Account address 也无效。事实上,以上内容充满了语法错误。
  • 这里的逻辑是合理的,但是代码中充满了语法错误。

标签: sql sql-server comparison


【解决方案1】:

实际上,您可以使用EXCEPT 表运算符: 喜欢这里:

WITH 
old_table(cust,accnt,addr) AS (
            SELECT 'AAAA',101,'AA1'
  UNION ALL SELECT 'BBBB',102,'BB1'
  UNION ALL SELECT 'CCCC',102,'BB1'
)
,
new_table AS (
            SELECT 'AAAA',101,'AA1'
  UNION ALL SELECT 'BBBB',102,'BB1'
  UNION ALL SELECT 'CCCC',102,'BB2'
)
(
SELECT * FROM old_table
EXCEPT
SELECT * FROM new_table
)
UNION ALL 
(
SELECT * FROM new_table
EXCEPT
SELECT * FROM old_table
)
;
-- out  cust | accnt | addr 
-- out ------+-------+------
-- out  CCCC |   102 | BB1
-- out  CCCC |   102 | BB2

【讨论】:

  • 嗨 Marcothesane,我的表有一百万条记录。我们有办法比较这两张表吗
【解决方案2】:

你少了很多逗号;)

WITH source AS  
(  
     SELECT ROW_NUMBER() OVER(ORDER BY Customer ,Account, address) AS RowN,   
    Customer,    Account ,address
FROM old
)  
, target AS  
(  
     SELECT ROW_NUMBER() OVER(ORDER BY Customer, Account ,address) AS RowN,   
    Customer,    Account, address
FROM New
)  

Select s.address , t.address 
from source s
join traget t on s.RowN =t.RowN
where s.Customer <> t.Customer
or s.Account <> t.Account
or s.address <> t.address

【讨论】:

  • 这仍然缺少很多逗号。查看 order by 子句。 ;)
  • @SeanLange 哈哈,谢谢;)
  • 嗨,eshirvana,谢谢!!!