I have a stored proc where I am deleting a row from a table.
Is there a way to return the ID of the row deleted? I know there's a way to do it with inserting (SCOPE_IDENTITY()), but it doesn't seem to work for deletions.
The code:
BEGIN
declare @returnVal int
DELETE FROM table WHERE num = 1;
set @returnVal = /*HOW TO GET ID OF ROW DELETED?*/
END;
Yes you can. From 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
You will have to run 2 commands: SELECT to retrieve ID and DELETE to actually perform deleteion.
BEGIN
declare @returnVal int
SELECT @returnVal = ID FROM table WHERE num = 1;
DELETE FROM table WHERE num = 1;
END;
Unless you delete based on ID - in that case you already know it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With