Saturday 10 March 2012

MS SQL 2012 - How to Create Simple Stored Procedure with Scope Identity



Scope_Identity() - returns last inserted record id (primary key) in scope (for instance stored procedure)

ALTER PROCEDURE [dbo].[InsertDept]
    @DeptName Varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Insert Into Dpt(DepartmentName) Values(@DeptName);
    Select Scope_Identity() as NewDepartment;
END

if you execute this stored procedure you will get id of the new department

No comments:

Post a Comment