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:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may