Yinfang Zhuang
Yinfang Zhuang

Reputation: 461

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

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

Upvotes: 24

Views: 67629

Answers (2)

dragonborn
dragonborn

Reputation: 21

I can't see why it is necessary to place the returned row value into a new variable @new_identity. I would simply include SELECT SCOPE_IDENTITY(); at the end of the stored procedure like this:

CREATE PROCEDURE dbo.AddAsset
  @Name VARCHAR(500),
  @URL  VARCHAR(2000)
AS
BEGIN
    SET NOCOUNT ON;

    INSERT dbo.Assets(Name, URL) SELECT @Name, @URL;
    SELECT SCOPE_IDENTITY();
END
GO

Upvotes: 2

Aaron Bertrand
Aaron Bertrand

Reputation: 280262

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.

Upvotes: 38

Related Questions