我想写一个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);
答案 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;