I know that in T-SQL (Server 2008 R2) I can use the ‘Output’ keyword to get the Id of a row I just inserted. For example, I can do
insert into [Membership].[dbo].[User] (EmailAddress)
output Inserted.UserId
values('testUser1@test.com')
Is there any way of composing this into another insert? For example, lets say I want to add a new user and immediately add that user to a UserRole table which maps the UserId to a RoleId.
Basically, I would like to do something like below.
insert into UserRole (RoleId, UserId)
values
(
1,
insert into [Membership].[dbo].[User] (EmailAddress)
output Inserted.UserId values('testUser1@test.com')
)
But I can’t seem to get this to work. I tried wrapping the internal insert in brackets () or using a select * from () etc.
What am I missing? Is this composition even possible?
Thanks for the help.
Regards,
You would have to capture the output into a table variable:
and then in a second step do an insert from that temp table into the target table:
You could also direct the
OUTPUTclause directly into the target table – that’ll work if you can e.g. use a fixed value for yourRoleID: