我正在尝试执行更新和选择...基本上,基于索引进行更新,然后选择已更新的行 ID。
使用 OUTPUT 子句很简单:
UPDATE Foo
SET Bar = 1
OUTPUT INSERTED.Id
WHERE Baz = 2
但是现在,我如何把它变成一个变量?
DECLARE @id INT
这三个不起作用:
UPDATE Foo
SET Bar = 1
OUTPUT @id = INSERTED.Id
WHERE Baz = 2
SET @id =
(UPDATE Foo
SET Bar = 1
OUTPUT INSERTED.Id
WHERE Baz = 2)
SET @id =
(SELECT Id FROM (UPDATE Foo
SET Bar = 1
OUTPUT INSERTED.Id Id
WHERE Baz = 2) z)
最后一个包括在内,因为当所有红色波浪线在 Management Studio 中消失时,它让我暂时感到兴奋。唉,我得到这个错误:
A nested INSERT, UPDATE, DELETE, or MERGE statement is not allowed in a SELECT statement that is not the immediate source of rows for an INSERT statement.