Blog » SQL Tips: Insert Value using Identity from Previous Insert

SQL Tips: Insert Value using Identity from Previous Insert

Ever find yourself needing to write SQL code to run on multiple tables where one of the values in a secondary INSERT statement is dependent upon the identity value from previous insert? Well, if so, this should work for you…

[code language=”sql”]DECLARE @NewApiId int;
INSERT INTO APIs (Name, Description) VALUES (‘Social Links’,’The Social Links API, available only to corporate clients, will output a report all of the clients for the client”s ClientTypeID that includes all of the recorded social media properties’);
SELECT @NewApiId = CAST(scope_identity() AS int);
INSERT INTO ApiSubscriptions (ApiId, ClientId) VALUES (@NewApiId, 666);
select * from APIs;
Select * from APISubscriptions WHERE ClientId=666;[/code]

Pretty simple, no?

Michael Gibbs
Stalk Me...
Latest posts by Michael Gibbs (see all)