Obtaining @@Identity with VBScript and ADO

Question:
Using VBScript, how can I use the @@Identity SQL Statement to set the keyfield of a record just entered to a variable?

Answer:

You can issue multiple SQL statements within a single ADO Execute statement. Just separate the statements with a carriage return – vbCrLf.

To get the @@Identity SQL Statement back for a just inserted row, you need to issue a ‘SELECT @@Identity’ statement within your original insert statement itself. For example, say, you were inserting a row in a table called Test. Your SQL Statement would then look like this:

"INSERT INTO Test (field1, field2) Values (value1, value2)"

To then obtain the Identity field (say field0) value of the just inserted row, you would need to use the following SQL Statement:

"SELECT @@Identity"

You can either write a stored procedure in SQL Server that concatenates the above two SQL statements and returns the Identity field value, or you can concatenate them within a single ADO query itself.

strSQL = "INSERT INTO Test (field1, field2) Values (value1, value2)"strSQL = strSQL & vbCrLfstrSQL = strSQL & "SELECT @@Identity"strSQL = strSQL & vbCrLf

When you execute that SQL statement, you will obtain a single row recordset back that contains the Identity field value. You can access that value by using the Recordset(0) notation.

Dim objRS, lngIdentityValueset objRS = Connection.Execute (strSQL)lngIdentityValue = objRS(0)set objRS = Nothing

Note that the above works with SQL Server 7. I have not tested it with other databases.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

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