Categories
SQL

Get the ID of the Inserted row

One way of getting the ID of the row you just inserted into a table would be to run another sql statement following the insert one. Use an aggreagate statement something like SELECT MAX (CusID from tblCustomers.

You can also get it using the insert statement with the OUTPUT clause…

INSERT INTO tblCustomers (FirstName, LastName) OUTPUT INSERTED.CusID
VALUES (‘Fred’, ‘Bloggs’)

(Assuming CusID is the primary key field in the table.)

If you’re running the insert in an application, the command needs to ExecuteScalar rather than just Execute…

In C#:

Return (Int32)cmd.ExecuteScalar();

Leave a Reply

Your email address will not be published.