I am currently working in C#, and I need to insert a new record into one table, get the new primary key value, and then use that as a foreign key reference in inserting several more records. The Database is MS SQL Server 2003. All help is appreciated!
Share
The way to get the identity of the inserted row is with the
SCOPE_IDENTITY()function. If you’re using stored procedures then this would look something like the following to return the row identity as an output parameter.You can then use this value for any subsequent inserts (alternatively, if you can pass the data all into the stored procedure, then you can use it in the remainder of the procedure body).
If you’re passing the SQL in dynamically then you use much the same technique, but with a single string with statement delimiters (also
;in SQL), e.g.:Then if you execute this using
ExecuteScalaryou’ll be able to get the identity back as the scalar result and cast it to the right type. Alternatively you could build up the whole batch in one go, e.g.This may not be exactly the right syntax, and you may need to use
SET NOCOUNT ON;at the start (my mind is rusty as I rarely use dynamic SQL) but it should get you on the right track.