4

我有一个存储过程,我正在从表中删除一行。

有没有办法返回已删除行的 ID?我知道有一种插入(SCOPE_IDENTITY())的方法,但它似乎不适用于删除。

编码:

BEGIN   
  declare @returnVal int
  DELETE FROM table WHERE num = 1;

  set @returnVal = /*HOW TO GET ID OF ROW DELETED?*/
END;
4

3 回答 3

7

是的你可以。从这里:-

CREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))
----Creating temp table to store ovalues of OUTPUT clause
DECLARE @TmpTable TABLE (ID INT, TEXTVal VARCHAR(100))
----Insert values in real table
INSERT TestTable (ID, TEXTVal)
VALUES (1,'FirstVal')
INSERT TestTable (ID, TEXTVal)
VALUES (2,'SecondVal')
----Update the table and insert values in temp table using Output clause
DELETE
FROM TestTable
OUTPUT Deleted.ID, Deleted.TEXTVal INTO @TmpTable
WHERE ID IN (1,2)
----Check the values in the temp table and real table
----The values in both the tables will be same
SELECT * FROM @TmpTable
SELECT * FROM TestTable
----Clean up time
DROP TABLE TestTable
GO
于 2013-10-17T18:19:34.470 回答
2

您必须运行 2 个命令:SELECT 检索 ID 和 DELETE 实际执行删除。

BEGIN   
  declare @returnVal int
  SELECT @returnVal = ID FROM table WHERE num = 1;
  DELETE FROM table WHERE num = 1;
END;

除非您根据 ID 删除 - 在这种情况下您已经知道它。

于 2013-10-17T18:20:31.670 回答
1

只需在and之间插入一个OUTPUT子句:DELETE FROMWHERE

DECLARE @returnVal TABLE ([id] [int] NOT NULL)

DELETE FROM table
  OUTPUT deleted.[id] INTO @returnVal 
  WHERE num = 1;

/* @returnVal contains the [id] values of all deleted rows. */

在语句中,您可以通过自动创建的表别名DELETE访问已删除行的数据。deleted

于 2020-04-26T12:06:57.323 回答