Tutorials

Retrieve new ID using a Command

This tutorial cover the use of the Command in Dreamweaver MX to insert a new record into a SQL Server database and retrieve the newly created identity number.

The first thing to do is to build a standard Insert command using the Command dialogue.

Once you have done that, delve into the code and modify as follows:

Find this line:
cmdInsert.CommandText = "INSERT INTO dbo.tblUser (UserName) VALUES ('" + Replace(cmdInsert__varUsername, "'", "''") + ") "

And replace it with this line:
cmdInsert.CommandText = "SET NOCOUNT ON;INSERT INTO dbo.tblUser (UserName) VALUES ('" + Replace(cmdInsert__varUsername, "'", "''") + ");SELECT @" & "@IDENTITY AS ID"

Find this line:
cmdInsert.Execute()

And replace it with the following:
Set rsID = cmdInsert.Execute()
IF (NOT rsID.EOF) THEN
     varLastID = rsID.Fields.Item("ID").Value
END IF

What happens here is the insert takes place and the newly created ID is retrieved and stuffed into a recordset. We then query the recordset for the new ID and assign it to a variable called varLastID.

Notes

Set rsID = cmdInsert.Execute()
IF (NOT rsID.EOF) THEN
     varLastID = rsID.Fields.Item("ID").Value
rsID.Close()
Set rsID = Nothing
END IF

Thats it!

There are several ways and explanations out there that cover Insert and Retrieve ID's using standard Insert server behaviours in Dreamweaver MX - even some excellent extensions to do it, but nothing on using the Command to do the same thing - so here it is!

I hope this helps someone.