Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a stored procedure that inserts a row and returns the ID

Tags:

I tried to write a stored procedure that first inserts a new record into table and then returned the id of this new record. I am not sure if it is the correct way and the best way to achieve this.

ALTER PROCEDURE dbo.spAddAsset ( @Name VARCHAR(500), @URL VARCHAR(2000) ) AS BEGIN Set NOCOUNT on;  Insert Into Assets (Name, URL) Values (@Name, @URL)  Declare @new_identity int;  SELECT @new_identity = SCOPE_IDENTITY()  return @new_identity; END 
like image 858
Yinfang Zhuang Avatar asked Mar 04 '12 18:03

Yinfang Zhuang


People also ask

How can we return a value in stored procedure?

Return Value in SQL Server Stored Procedure In default, when we execute a stored procedure in SQL Server, it returns an integer value and this value indicates the execution status of the stored procedure. The 0 value indicates, the procedure is completed successfully and the non-zero values indicate an error.

What is SCOPE_IDENTITY () in SQL?

SCOPE_IDENTITY() returns the IDENTITY value inserted in T1. This was the last insert that occurred in the same scope. The SCOPE_IDENTITY() function returns the null value if the function is invoked before any INSERT statements into an identity column occur in the scope.


1 Answers

To return a single scalar value to the caller you should use an OUTPUT parameter, not RETURN. RETURN is for error/status codes. Also the prefix sp is redundant and unnecessary.

CREATE PROCEDURE dbo.AddAsset   @Name VARCHAR(500),   @URL  VARCHAR(2000),   @new_identity INT = NULL OUTPUT AS BEGIN     SET NOCOUNT ON;      INSERT dbo.Assets(Name, URL) SELECT @Name, @URL;     SET @new_identity = SCOPE_IDENTITY(); END GO 

Then to call it:

DECLARE @new_identity INT; EXEC dbo.AddAsset @Name = 'a', @URL = 'b', @new_identity = @new_identity OUTPUT; PRINT @new_identity; 

EDIT just adding a disclaimer that won't affect the asker in this specific scenario, but may help in other scenarios or for future readers. In SQL Server 2008 R2 and earlier, there is a potentially nasty bug with built-in functions such as SCOPE_IDENTITY when parallelism is used to derive the results to be inserted (think INSERT FROM othertable). This bug (here is the Connect item) is fixed in Cumulative Update #5 for SQL Server 2008 R2 SP1, but so far a fix has not appeared for 2008 R2 RTM, 2008 or 2005.

like image 162
Aaron Bertrand Avatar answered Nov 02 '22 23:11

Aaron Bertrand