Insert record newly inserted ID into child records SQL Server OUTPUT clause -


i have projectstaging table want insert records project table based on no match on stagingid field. project table has own auto incrementing projectid. part if fine (using not exists).

next want create 3 projectlineitems each inserted project newly inserted projectid , default settings of 1, 2 , 3 in status field. using output extract projectid, saving id temptable , storing in variable @newprojectid later on inserting 3 line items. getting error saying projectid null. why be? output id not making temptable?

---here's sql

declare @newprojectid int declare @temptable table(id int)   insert project     (     stagingid,     field1,     field2     )     output inserted.projectid @temptable(id)     select     stagingid,     field1,     field2     projectstaging not exists (     select * projectstaging project.stagingid = projectstaging.stagingid)      select @newprojectid = id @temptable       insert projectlineitems(projectid, status) values(@newprojectid, 1)     insert projectlineitems(projectid, status) values(@newprojectid, 2)     insert projectlineitems(projectid, status) values(@newprojectid, 3) 

rather output inside insert, have tried: select @newprojectid = (select ident_current('projectstaging'))

this set @newprojectid value of last inserted identity value projectid

any reason why wouldn't work you?

so new code be:

declare @newprojectid int  insert project     (     stagingid,     field1,     field2     )     select     stagingid,     field1,     field2     projectstaging not exists (     select * projectstaging project.stagingid = projectstaging.stagingid)      select @newprojectid = (select ident_current('projectstaging'))      insert projectlineitems(projectid, status) values(@newprojectid, 1)     insert projectlineitems(projectid, status) values(@newprojectid, 2)     insert projectlineitems(projectid, status) values(@newprojectid, 3) 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -