UPDATE按源表和目标表中的值排序

时间:2015-07-22 21:26:50

标签: sql-server sql-server-2008 tsql

考虑以下示例:

DECLARE @UPD TABLE
(KeyToFillIn Int,
SomeDataToCompare Int,
Ordinal Int)

DECLARE @SRC TABLE
(KeyS Int,
SomeDataToCompare Int)

INSERT @UPD VALUES (NULL, 100, 1)
INSERT @UPD VALUES (NULL, 100, 2)
INSERT @UPD VALUES (NULL, 100, 3)
INSERT @UPD VALUES (NULL, 100, 4)

INSERT @SRC VALUES (12, 100)
INSERT @SRC VALUES (280, 100)
INSERT @SRC VALUES (232, 100)
INSERT @SRC VALUES (1, 100)
INSERT @SRC VALUES (121, 100)
INSERT @SRC VALUES (123, 100)
INSERT @SRC VALUES (128, 100)

-- This update
UPDATE @UPD
SET KeyToFillIn = S.KeyS
FROM @UPD U INNER JOIN @SRC S ON U.SomeDataToCompare = S.SomeDataToCompare

SELECT * FROM @UPD
SELECT * FROM @SRC

我需要按顺序从SRC表更新UPD.KeyToFillIn。 SRC表可能没有相应的记录(由SomeDataToCompare匹配)。或者它可能有更多。但是我希望UPD表按顺序排序,也可以从KeyS中取得KeyToFillIn。因此,结果集看起来像

1   100 1 
12  100 2 
121 100 3 
123 100 4

2 个答案:

答案 0 :(得分:4)

这是你需要的吗?

;WITH UPD
     AS (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY SomeDataToCompare ORDER BY Ordinal) AS RN
         FROM   @UPD),
     SRC
     AS (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY SomeDataToCompare ORDER BY KeyS) AS RN
         FROM   @SRC),
     U
     AS (SELECT KeyToFillIn,
                KeyS
         FROM   UPD U
                INNER JOIN SRC S
                  ON U.SomeDataToCompare = S.SomeDataToCompare
                     AND S.RN = U.RN)
UPDATE U
SET    KeyToFillIn = KeyS

SELECT *
FROM   @UPD 

SQL Fiddle

答案 1 :(得分:1)

可能这也是有用的,因为我们可以在简单的更新语句中得到这个假设数据

UPDATE U SET KeyToFillIn = R.KeyS  from @UPD U
INNER JOIN (Select ROW_NUMBER() 
            OVER (PARTITION BY SomeDataToCompare ORDER BY KeyS) AS RN,
            KeyS,SomeDataToCompare 
                    from @SRC )R
ON R.RN = U.Ordinal

select * from @UPD