Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB7
Expertise: Intermediate
Dec 22, 2003

Retrieving the ID of the last inserted record

When you add a new record to a SQL Server table that has an identity column, you usually want to read back the auto-generated ID, for example to use it as a foreign key in another table. If you use stored procedures this is easy to do: just use an output parameter that you set as follows: SET @NewID = @@IDENTITY. However, there is a nice trick that you can use to easily retrieve the same value even if you use the ADO.NET's SqlCommand class with inline SQL (which I find much easier when you have dynamic queries - and they still are very fast if you use parameters, because the execution plan is cached anyway). The SqlCommand class allows you to concatenate multiple statements, separated by a ; char, and thus you can have the following SQL command:

Dim sql As String = "INSERT INTO jobs (job_desc,min_lvl,max_lvl) VALUES ('A new job', 25, 100);" & _
"SELECT job_id FROM jobs WHERE job_id = @@IDENTITY"
Dim cmd As New SqlCommand(sql, cn)

When you execute the command, the first statement is executed and the record is inserted. Then the second statement is executed, and the query returns the ID of the last inserted record, i.e. the record of the first statement. Since the query returns a single row with a single value, you can execute the command with its ExecuteScalar method, and cast the returned Object value to Integer as follows:


' insert the new row and read back the IDENTITY field
Dim jobId As Integer = CInt(cmd.ExecuteScalar())
Marco Bellinaso
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap