在执行 CTE Select Order By 然后更新后,更新结果的排序不同(TSQL)

After doing CTE Select Order By and then Update, Update results are not ordered the same (TSQL)

代码大致是这样的:

WITH cte AS
(
 SELECT TOP 4 id, due_date, check
 FROM table_a a
 INNER JOIN table_b b ON a.linkid = b.linkid
 WHERE
  b.status = 1
  AND due_date > GetDate()
 ORDER BY due_date, id
)
UPDATE cte
SET check = 1
OUTPUT
 INSERTED.id,
 INSERTED.due_date

注:实际数据相同due_date。

当我 运行 仅在 cte 内的 SELECT 语句时,我可以获得结果,例如:1、2、3、4。 但是UPDATE语句之后,更新的结果是:4,1,2,3

为什么会发生这种情况(订单更改)?

如何在同一个查询中将结果保留或重新排序为 1、2、3、4?

在 MSDN https://msdn.microsoft.com/pl-pl/library/ms177564(v=sql.110).aspx 你可以阅读

There is no guarantee that the order in which the changes are applied to the table and the order in which the rows are inserted into the output table or table variable will correspond.

这意味着您不能仅通过一个查询来解决您的问题。但是你仍然可以使用一批来做你需要的。因为您的输出不能保证顺序,所以您必须将其保存在另一个 table 中并在更新后对其进行排序。此代码将 return 您的输出值,以便您假设:

declare @outputTable table( id int, due_date date);

with cte as (
    select top 4 id, due_date, check
    from table_a a
    inner join table_b b on a.linkid = b.linkid
    where b.status = 1
    and due_date > GetDate()
    order by due_date, id
)
update cte
set check = 1
output inserted.id, inserted.due_date
into @outputTable;

select *
from @outputTable
order by due_date, id;