Getting the auto generated id after insert in MSSQL

With thanks to some smart people on the CFTalk mailing list, here is a concise strategy for getting an automatically generated primary key id after inserting a record into an MSSQL database.

Suppose you have a table Person with fields:

personId - int, auto Id, Primary Key
firstName - varchar
lastName - varchar

To insert a new record and retrieve the new record id you can use:

<cfquery name="personInsertQuery" datasource="mydsn">
   set nocount on
   insert into Person
   (
      firstName,
      lastName
   )
   values
   (
      <cfqueryparam cfsqltype="CF_SQL_VARCHAR"
         value="#firstName#">
,
      <cfqueryparam cfsqltype="CF_SQL_VARCHAR"
         value="#lastName#">

   );
   set nocount off
   select scope_identity() as personId;
</cfquery>

<cfset personId = personInsertQuery.personId>

Easy.

Comments
15 Mar 2007 08:24AM
James Allen said:
That is fantastic!! How many years have I (and I'm sure others) been doing the old INSERT, then immediately SELECT Max(ID) AS NewID FROM xxxx routine to get the newly inserted ID.. I always thought CFQUERY should be able to return the new ID and hear it is. Brilliant. Thanks for posting this.
13 Jun 2007 07:35AM
Joern said:
Does this work with mysql, too?
14 Jun 2007 01:55AM
Hi Joern

I am not sure, but it is unlikely.
10 Jul 2007 08:24AM
Hey, also note the new SQL Server 2005 feature - the OUTPUT clause:

<cfquery name="personInsertQuery" datasource="mydsn">
INSERT INTO Person(firstname,lastname)
OUTPUT
INSERTED.personID, INSERTED.firstname, INSERTED.lastname
VALUES (
<cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#firstname#">,
<cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#lastname#">
)
</cfquery>

Tony Brandner
13 Jul 2007 12:33AM
Hi Tony, thanks for the update!
29 Oct 2007 07:23AM
Eric Cobb said:
If you're using CF8, this is built into <CFQUERY> now:

http://www.forta.com/blog/index.cfm/2007/7/6/ColdF...
Add a comment
(will not be published)
(include http://)