2014-10-02 101 views
0

T-SQL UPDATE請考慮以下兩個表:雙ROW_NUMBER功能

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()功能IE)的信息傳輸到第二個你得到一個錯誤,或者如果你放棄了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 
+0

請發佈錯誤 – 2014-10-02 08:55:27

回答

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)相關,所以你有一個隱藏的交叉連接發生g在那裏。

+0

非常感謝!就是這樣! :) – ax1mx2 2014-10-02 08:58:14