Get the ID of Last Inserted Record in SQL Server
Sometimes you need to know the value of your Primary Key when you insert record in your table. This is true if you have a Master/Detail form and you need to know the Primary key value of the parent table so that you can insert rows in the related table.
Consider the following scenario:
You have and Invoice table with InvoiceDetails as the related table. Invoice table has primary key named “InvoiceID” and in your InvoiceDetails you also have InvoiceID as a foreign key. Before you can insert record in the related table (i.e. in InvoiceDetails), you need to know the value of the InvoiceID from your primary table.
Of course you only need to get the value of InvoiceID if this column is an Identity in your SQL Server table or autoincrement in MS Access database.
The technique is very simple by simply adding the SELECT SCOPE_IDENTITY();
at the end of your INSERT statement. Then using ExecuteScalar()
instead of ExecuteNonQuery().
Sample code:
- Dim cmd As SqlCommand = New SqlCommand(strSQL, conn)
- Dim identity As Integer
- identity = Integer.Parse(cmd.ExecuteScalar().ToString())
To learn more on this matter please refer to “Sample Invoice with Master/Detail Form”.
Comments
Add new comment
- Add new comment
- 131 views