为表的差异添加唯一的ID号

时间:2016-06-09 09:13:23

标签: sql sql-server

我正在使用此查询来查找我需要插入到B中的同一个表上的两个不同数据库(A和B)之间的行差异:

(select recordkey, class, relatedreckey, relatedrecclass, relatetype
from A.dbo.relatedrecord
group by recordkey, class, relatedreckey, relatedrecclass, relatetype)
EXCEPT
(select recordkey, class, relatedreckey, relatedrecclass, relatetype
from B.dbo.relatedrecord
group by recordkey, class, relatedreckey, relatedrecclass, relatetype)

我现在面临的问题是有一个名为RELATEDRECORDID的唯一id列,我需要为这些结果行中的每个结果行填充序列(max(B.dbo.relatedrecordid)+1)。

如何在原始查询中包含此唯一ID生成?

2 个答案:

答案 0 :(得分:0)

为什么不在select查询之外使用SQL Row_Number() function。我的意思是将两个选择放在SQL CTE表达式中,并在SELECT列表中为Row_Number()添加一个新列,其中Order By子句将为每行返回一个唯一的数字

例如,您可以修改以下Select语句

;with cte as (

(select recordkey, class, relatedreckey, relatedrecclass, relatetype
from A.dbo.relatedrecord
group by recordkey, class, relatedreckey, relatedrecclass, relatetype)
EXCEPT
(select recordkey, class, relatedreckey, relatedrecclass, relatetype
from B.dbo.relatedrecord
group by recordkey, class, relatedreckey, relatedrecclass, relatetype)

)
select row_number() over (order by recordkey, class, relatedreckey, relatedrecclass, relatetype) rn, * from cte

答案 1 :(得分:0)

Hello AuthenticReplica,

我在现有的表达中添加了一个新的CTE表达式。您可以在SQL中定义multiple CTE queries。第二个仅用于最大值

请查看以下查询

with cte as (
select * 
from sys.tables
), maxid as (
    select MAX(OBJECT_ID) maxid from sys.tables
)
select 
    rn = maxid + ROW_NUMBER() over (order by name), *
from cte
cross join maxid