SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

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

*/

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


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

SQL Server 2012 is a program product of Microsoft Corporation.
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.