通过DELETE输出时发生意外的ROW_NUMBER行为

时间:2018-09-03 07:51:56

标签: tsql window-functions

我希望[version]会在下面的#X中大于1,但是似乎ROW_NUMBER在进入#X的途中被重新评估了。这是预期的行为,有什么方法可以防止它发生?

DROP TABLE IF EXISTS #T;
CREATE TABLE #T (id INT, v CHAR(1));
INSERT INTO #T VALUES (1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (2, 'c');
DROP TABLE IF EXISTS #X;
SELECT TOP 0 *, 1 AS [version] INTO #X FROM #T;
DELETE t OUTPUT deleted.* INTO #X FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY v) AS [version] FROM #T
) t WHERE t.[version] > 1;
SELECT * FROM #X;

0 个答案:

没有答案