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.

This entry was posted in MSSQL and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

6 Comments

  1. James Allen
    Posted March 15, 2007 at 8:24 am | Permalink

    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.

  2. Posted June 13, 2007 at 7:35 am | Permalink

    Does this work with mysql, too?

  3. Posted June 14, 2007 at 1:55 am | Permalink

    Hi Joern

    I am not sure, but it is unlikely.

  4. Posted July 10, 2007 at 8:24 am | Permalink

    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

  5. Posted July 13, 2007 at 12:33 am | Permalink

    Hi Tony, thanks for the update!

  6. Posted October 29, 2007 at 7:23 am | Permalink

    If you’re using CF8, this is built into <CFQUERY> now:

    http://www.forta.com/blog/index.cfm/2007/7/6/ColdFusion-8-Can-Return-Identity-Values

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">