Since you are on SQL Server you can use the SCOPE_IDENTITY()
function to safely grab the last inserted identity value in the current scope.
The documentation says
SCOPE_IDENTITY (Transact-SQL)
Returns the last identity value inserted into an identity column in
the same scope. A scope is a module: a stored procedure, trigger,
function, or batch. Therefore, two statements are in the same scope if
they are in the same stored procedure, function, or batch.
When used in two separate ColdFusion tags (<cfinsert>
followed by <cfquery>
) then that's two batches and SCOPE_IDENTITY()
will not work anymore. Therefore the INSERT
and the SELECT
statement will have to be part of the same batch. Unfortunately this cannot be achieved with <cfinsert>
.
You said you had many fields in your form post, so I would do something like this:
<cfset fieldNames = "all,relevant,field,names,from,http,post">
<cfset fieldTypes = "INTEGER,VARCHAR,VARCHAR,DATETIME,INTEGER,VARCHAR,VARCHAR">
<cfset fieldNullable = "false,true,true,true,false,true,false">
<cfset fieldCount = ListLen(fieldNames)>
<!--- default "" for any fields missing from the HTTP POST --->
<cfloop from="1" to="#fieldCount#" index="i">
<cfparam name="FORM.#ListGetAt(fieldNames, i)#" default="">
</cfloop>
<cfquery name="insert" datasource="#yourdatasource#">
INSERT YourTable (#fieldNames#)
VALUES (
<cfloop from="1" to="#fieldCount#" index="i">
<cfif i gt 1>,</cfif>
<cfset val = FORM[ListGetAt(fieldNames, i)]>
<cfset type = "CF_SQL_#ListGetAt(fieldTypes, i)#">
<cfset null = ListGetAt(fieldNullable, i) eq "true" and val eq "">
<cfqueryparam value="#val#" cfsqltype="#type#" null="#null#">
</cfloop>
)
SELECT SCOPE_IDENTITY() as NewId
</cfquery>
<cfdump var="#insert#">
<cfinsert>
? Maybe<cfquery>
with one INSERT statement to insert the data and one SELECT statment to grab the new ID would be a useful alternative. – VenositySELECT MAX(id)
will return the same value. – VenositySCOPE_IDENTITY
to solve this particular problem. Other DB systems use different functions. So, it depends. – Venosity<cfinsert>
or not. You see, if you only had answered the two questions in my first comment... – VenosityMAX(id)
useSELECT SCOPE_IDENTITY() as NewId
in a cfquery. – VenositySCOPE_IDENTITY
even return a value when used like that? – Venositycfinsert
.....ever. – Dextrous