SQLUSA
BI TRIO 2008
FREE TRIAL
CLICK HERE TO ORDER

SQL Server 2008 Best Practices
SQL Server 2005 Best Practices

How to apply the scope_identity function in an INSERT sproc?

Execute the following T-SQL script in Query Editor to create and apply a a stored procedure which captures the identity just created by the INSERT statement on the identity(1,1) surrogate key column using the SCOPE_IDENTITY() function, an alternate to @@IDENTITY.

USE AdventureWorks

GO

-- SQL Server stored procedure - Primary key identity insert

CREATE PROC [Production].uspInsertLocation

           @LocationID   INT  OUTPUT,

           @Name         CHAR(30),

           @CostRate     SMALLMONEY,

           @Availability DECIMAL(8,2)

AS

  BEGIN

    SET NOCOUNT  ON

    

    --Error Handling Start

    DECLARE  @ReturnValue INT

    

    SELECT @ReturnValue = 0

    

    -- Insert

    INSERT INTO [AdventureWorks].[Production].[Location]

               ([Name],

                [CostRate],

                [Availability],

                [ModifiedDate])

    SELECT @Name,

           @CostRate,

           @Availability,

           getdate()

    

    --Error Handler Catch

    SELECT @ReturnValue = @@ERROR

    

    SET @LocationID = scope_identity()

    

    EXITPOINT:

    

    RETURN @ReturnValue

  END

 

GO

 

-- SQL execution script

DECLARE  @LocationID INT

 

EXEC [Production].uspInsertLocation

  @LocationID OUTPUT ,

  'Paint Dryer Room' ,

  5.0 ,

  90.00

 

SELECT [New ID Assigned] = @LocationID

GO

/* Result

 

New ID Assigned

61

*/

 

The World Leader in SQL Server 2008 Training
The future is just a CLICK away. Your future!
 
SQLUSA.com Home Page

Copyright 2005-2010, SMI Corp. All Rights Reserved.

SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.