Retrieving the ID of the last inserted record

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 fieldDim jobId As Integer = CInt(cmd.ExecuteScalar())

Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved