Using output keyword to get last inserted records in SQL server? -
i have this tool (ssms tools pack ) generates crud sp's specific table
but ive @ "insert" code
/*1*/ create proc [dbo].[usp_eservices_me_country_infoinsert] /*2*/ @masterentityid int, /*3*/ ... /*4*/ /*5*/ set nocount on /*6*/ set xact_abort on /*7*/ /*8*/ begin tran /*9*/ /*10*/ insert [dbo].[eservices_me_country_info] ([masterentityid],...) /*11*/ select @masterentityid, ... /*12*/ /*13*/ -- begin return select <- not remove /*14*/ select [id], [masterentityid],... /*15*/ [dbo].[eservices_me_country_info] /*16*/ [id] = scope_identity() /*17*/ -- end return select <- not remove /*18*/ /*19*/ commit /*20*/ go
my question line #14 -- they/i use output
keyword ? , if , output
return all inserted records ? ( if there's >1 inserted records @ line #11 )
interesting question! based on info on output
clause here, think change this:
insert [dbo].[eservices_me_country_info] ([masterentityid],...) select @masterentityid, ... -- begin return select <- not remove select [id], [masterentityid],... [dbo].[eservices_me_country_info] [id] = scope_identity() -- end return select <- not remove
to this:
insert [dbo].[eservices_me_country_info] ([masterentityid],...) output inserted.masterentityid, ... select @masterentityid, ...
with same result. theory now, i'll go test , follow up.
follow up:
my output
clause not correct, have use output
right after insert
clause. edited in query above. used following code test this:
-- create test table create table testtable ( id int identity ,testv1 int ,testv2 int ,testv3 int ); go -- example sp 'old' method using scope_identity() create procedure usp_insertfirstmethod ( @v1 int ,@v2 int ,@v3 int ) set nocount on set xact_abort on begin tran insert dbo.testtable (testv1, testv2, testv3) select @v1, @v2, @v3; -- begin return select <- not remove select id, testv1, testv2, testv3 dbo.testtable id = scope_identity() -- end return select <- not remove commit tran; go -- example sp show use of output clause create procedure usp_insertsecondmethod ( @v1 int ,@v2 int ,@v3 int ) set nocount on set xact_abort on begin tran insert dbo.testtable (testv1, testv2, testv3) output inserted.* select @v1, @v2, @v3; commit tran; go
both execute dbo.usp_insertfirstmethod 1, 2, 3;
, execute dbo.usp_insertsecondmethod 1, 2, 3;
display same results. seems work!
Comments
Post a Comment