5

我想编写一个 MERGE 语句,通过使用 ORDER BY 子句从大表中选择前 10 行并将其更新为列值之一。MERGE 语句允许我选择 TOP 10 行,但我无法将 ORDER BY 子句放在任何地方。

MERGE TOP(10) StudentAllocation AS SA
USING (SELECT @sub_id AS subId) AS TSA ON SA.sub_id = TSA.subId
WHEN MATCHED THEN 
       UPDATE SET SA.exam_batch = 1);
4

1 回答 1

8

您可以将表表达式用作MERGE.

WITH SA AS
(
SELECT TOP(10) sub_id,
               exam_batch 
FROM StudentAllocation 
ORDER BY sub_id
)
MERGE SA
USING (SELECT @sub_id AS subId) AS TSA ON SA.sub_id = TSA.subId
WHEN MATCHED THEN 
       UPDATE SET SA.exam_batch = 1;

虽然使用起来可能更简单

WITH SA AS
(
SELECT TOP(10) sub_id,
               exam_batch 
FROM StudentAllocation 
ORDER BY sub_id
)
UPDATE SA
SET exam_batch = 1
WHERE sub_id = @sub_id;
于 2012-03-05T12:43:33.520 回答