我有一个存储过程,我从表中删除一行。
有没有办法返回删除的行的ID?我知道有一种方法可以插入(SCOPE_IDENTITY()),但它似乎不适用于删除。
代码:
BEGIN
declare @returnVal int
DELETE FROM table WHERE num = 1;
set @returnVal = /*HOW TO GET ID OF ROW DELETED?*/
END;
答案 0 :(得分:7)
是的,你可以。来自here: -
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
答案 1 :(得分: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删除 - 在这种情况下您已经知道了。
答案 2 :(得分:1)
只需在OUTPUT
和DELETE FROM
之间插入WHERE
子句:
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
表别名来访问已删除行的数据。