Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Stored Proc: Return ID of row deleted?

Tags:

sql

sql-server

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;
like image 716
Henley Avatar asked Dec 26 '22 19:12

Henley


2 Answers

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
like image 137
Rahul Tripathi Avatar answered Dec 28 '22 08:12

Rahul Tripathi


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.

like image 29
Yuriy Galanter Avatar answered Dec 28 '22 09:12

Yuriy Galanter