SQL Server MERGE语句和ORDER BY子句

时间:2012-03-05 12:41:29

标签: sql-server sql-order-by merge-statement

我想写一个MERGE语句,通过使用ORDER BY子句从一个大表中选择TOP 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);

1 个答案:

答案 0 :(得分: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;