Friday, August 16, 2013

Insert and get the ID of Same Row in SQL using scope_identity().

You need declare a output variable to get the autoincrement id inserted in the table.
    ,@JVID as int=null output
After Insert statement

use the following Select statement to get the field of inserted row in a procedure


select @JVID= SCOPE_IDENTITY()

select @JVID
and hence is beneficial for quiries which stores in more than one table and needs data or id of one table while inserting data in next table eg. in case of tables with relation ships or inheritance.

example:
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[prInsert_JournalMaster]
            @JVNo as nvarchar(25) =null
            ,@JVDate as datetime=null
           ,@ReceiptNo as int=null
           ,@ChequeAmount as nvarchar(1024)=null         
           ,@Year as nvarchar(100)=null
            ,@Month as nvarchar(100)=null
            ,@JVID as int=null output
            ,@ModuleName as nvarchar(100)=null
            ,@gov_budgetsubheadid as int=null
          
AS
BEGIN


INSERT INTO [tbl_JournalMaster]
           (
            [JVNo]  
           ,[JVDate]
           ,[Month]
            ,ModuleName
            ,gov_budgetsubheadid
            ,fiscalyearid
            )
     VALUES
           (
            @JVNo
           ,@JVDate
           ,@Month
            ,@ModuleName
            ,@gov_budgetsubheadid
            ,@fiscalyearid
           )
select @JVID=SCOPE_IDENTITY()

select @JVID
END