sql - How do I use an INSERT statement's OUTPUT clause to get the identity value? -


if have insert statement such as:

insert mytable (     name,   address,   phoneno ) values (   'yatrix',    '1234 address stuff',    '1112223333' ) 

how set @var int new row's identity value (called id) using output clause? i've seen samples of putting inserted.name table variables, example, can't non-table variable.

i've tried ouput inserted.id @var, set @var = inserted.id, neither have worked.

thanks in advance.

you can either have newly inserted id being output ssms console this:

insert mytable(name, address, phoneno) output inserted.id values ('yatrix', '1234 address stuff', '1112223333') 

you can use e.g. c#, when need id calling app - execute sql query .executescalar() (instead of .executenonquery()) read resulting id back.

or if need capture newly inserted id inside t-sql (e.g. later further processing), need create table variable:

declare @outputtbl table (id int)  insert mytable(name, address, phoneno) output inserted.id @outputtbl(id) values ('yatrix', '1234 address stuff', '1112223333') 

this way, can put multiple values @outputtbl , further processing on those. use "regular" temporary table (#temp) or "real" persistent table "output target" here.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -