Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored procedure - return identity as output parameter or scalar

When you insert a record into a table with an identity column, you can use SCOPE_IDENTITY() to get that value. Within the context of a stored procedure, which would be the recommended way to return the identity value:

  1. As an output parameter SET @RETURN_VALUE = SCOPE_IDENTITY()
  2. As a scalar SELECT SCOPE_IDENTITY()
  3. Another way?

Any pros/cons to each?

like image 515
Nelson Rothermel Avatar asked Jun 29 '10 15:06

Nelson Rothermel


People also ask

How can we return identity value from stored procedure in SQL Server?

When you insert a record into a table with an identity column, you can use SCOPE_IDENTITY() to get that value. Within the context of a stored procedure, which would be the recommended way to return the identity value: As an output parameter SET @RETURN_VALUE = SCOPE_IDENTITY() As a scalar SELECT SCOPE_IDENTITY()

Which parameter used to return values in procedure?

Return data using an output parameter. If you specify the output keyword for a parameter in the procedure definition, the procedure can return the current value of the parameter to the calling program when the procedure exits.

What is the difference between parameter and output parameter in stored procedure?

An input/output parameter is a parameter that functions as an IN or an OUT parameter or both. The value of the IN/OUT parameter is passed into the stored procedure/function and a new value can be assigned to the parameter and passed out of the module. An IN/OUT parameter must be a variable, not a constant.

What is return type of stored procedure?

A stored procedure does not have a return value but can optionally take input, output, or input-output parameters. A stored procedure can return output through any output or input-output parameter.


1 Answers

Another option would be as the return value for the stored procedure (I don't suggest this though, as that's usually best for error values).

I've included it as both when it's inserting a single row in cases where the stored procedure was being consumed by both other SQL procedures and a front-end which couldn't work with OUTPUT parameters (IBATIS in .NET I believe):

CREATE PROCEDURE My_Insert     @col1            VARCHAR(20),     @new_identity    INT    OUTPUT AS BEGIN     SET NOCOUNT ON      INSERT INTO My_Table (col1)     VALUES (@col1)      SELECT @new_identity = SCOPE_IDENTITY()      SELECT @new_identity AS id      RETURN END 

The output parameter is easier to work with in T-SQL when calling from other stored procedures IMO, but some programming languages have poor or no support for output parameters and work better with result sets.

like image 81
Tom H Avatar answered Sep 18 '22 18:09

Tom H