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:
SET @RETURN_VALUE = SCOPE_IDENTITY()
SELECT SCOPE_IDENTITY()
Any pros/cons to each?
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()
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.
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.
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.
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.
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