带有双ROW_NUMBER函数的T-SQL UPDATE

时间:2014-10-02 08:49:53

标签: sql sql-server tsql

考虑以下两个表:

CREATE TABLE [dbo].[names1](
    [dept] [varchar](3) PRIMARY KEY,
    [name] [varchar](20)
)

CREATE TABLE [dbo].[names2](
    [dept] [varchar](3) PRIMARY KEY,
    [name] [varchar](20)
)

在每个中插入相等数量的行(多于两个),但尽可能在主键字段中使用不同的值。

问题是:为什么然后当您尝试以顺序方式(即使用ROW_NUMBER()函数)将信息从第一个表传输到第二个表时,您会收到错误,或者如果你删除了PRIMARY KEY约束,错误的值?我怎样才能解决这个问题?我不想通过DELETEINSERT查询。

查询如下:

UPDATE
    names2
SET
    dept = n1.dept,
    name = n1.name
FROM (SELECT ROW_NUMBER() OVER (ORDER BY dept) AS RN, * from names2) AS n2,
     (SELECT ROW_NUMBER() OVER (order BY dept) AS RN, * from names1) AS n1 
WHERE n1.RN  = n2.RN

1 个答案:

答案 0 :(得分:1)

尝试使用别名n2作为UPDATE的目标:

UPDATE
    n2
SET
    dept = n1.dept,
    name = n1.name
FROM (SELECT ROW_NUMBER() OVER (ORDER BY dept) AS RN, * from names2) AS n2,
     (SELECT ROW_NUMBER() OVER (order BY dept) AS RN, * from names1) AS n1 
WHERE n1.RN  = n2.RN

目前看来,我认为最终names2UPDATE 的目标与n2无关(n1因此你在那里发生了隐藏的交叉连接。