Monday, 9 November 2009

Little cfquery gotcha

Here's something I do quite regularly:

<cfquery name="myquery" datasource="dsn">
INSERT INTO foo VALUES ('bar')
SELECT SCOPE_IDENTITY() as newId
</cfquery>

<cfset dosomethingwith = myquery.newId />
This is all good until you do something like:
<cfquery name="myquery" datasource="dsn">
INSERT INTO foo SELECT 'bar'
SELECT SCOPE_IDENTITY() as newId
</cfquery>

<cfset dosomethingwith = myquery.newId />
For whatever reason, CF craps out here and complains that 'myquery' is not defined. The problem only occurs, as far as I am aware, when you use SELECT syntax in your INSERT statement, something that is often neccessary. The workaround is straightforward, thankfully:

<cfquery name="myquery" datasource="dsn">
DECLARE @newId int

INSERT INTO foo SELECT 'bar'

SET @newId = SCOPE_IDENTITY()
SELECT @newId as newId
</cfquery>

<cfset dosomethingwith = myquery.newId />
Thanks to Neil Smith for the work around; I'd been using a separate query with @@identity for some time until today - far from good.

Dom

4 comments:

AzaWaza said...

have you tried using RESULT attribute of cfquery tag? i do not have a handy ms sql server to test it myself, but i wonder if this would return the new id without crapping out:
<cfquery name="myquery" datasource="dsn" result="myqueryresult">
INSERT INTO foo SELECT 'bar'
</cfquery>
>cfset dosomethingwith = myqueryresult.identitycol /<

Azadi

Dom said...

I recall a post by Adrian Lynch back in April 08, that suggests it won't work:

http://www.houseoffusion.com/groups/cf-talk/thread.cfm/threadid:55225#304092

That's not to say it doesn't, of course, I'll try it out...

Ben Nadel said...

This might be trivial, but would adding a ";" after each logical statement affect the error at all?

Dom said...

An update, I've tried using both the result attribute and semicolons after each statement with no joy (same crashing result).