考虑以下两个表:
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
约束,错误的值?我怎样才能解决这个问题?我不想通过DELETE
和INSERT
查询。
查询如下:
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
答案 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
目前看来,我认为最终names2
(UPDATE
的目标与n2
无关(n1
因此你在那里发生了隐藏的交叉连接。