Inserting multiple records using one INSERT INTO statement and SQL Server
As seen on Adam Presley's blog entry it is possible to insert more than one record using only one call to SQL server.
<cfquery name="test" datasource="#this.dsn#" result="testResult"> INSERT INTO contacts ( firstname ,lastname ) SELECT <cfqueryparam cfsqltype="cf_sql_varchar" value="Marko"> ,<cfqueryparam cfsqltype="cf_sql_varchar" value="Simic"> UNION ALL SELECT <cfqueryparam cfsqltype="cf_sql_varchar" value="Boris"> , <cfqueryparam cfsqltype="cf_sql_varchar" value="Huskic"> </cfquery> <cfdump var="#testResult#"> <cfdump var="#testResult.IDENTITYCOL#">
BUT, there's one down side of this approach. Since I always use *.IDENTITYCOL as return from set method I checked if I'll maybe get some kind of array of inserted records... The answer is. my friend, no. (At least for CF8)
Element IDENTITYCOL is undefined in TESTRESULT.
In SQL server 2008 you could even simplify above statement and write this:
<!--- SQL Server 2008 ---> <cfquery name="test" datasource="#this.dsn#" result="testResult"> INSERT INTO contacts ( firstname ,lastname ) VALUES ( ( <cfqueryparam cfsqltype="cf_sql_varchar" value="Marko"> , <cfqueryparam cfsqltype="cf_sql_varchar" value="Simic">), ( <cfqueryparam cfsqltype="cf_sql_varchar" value="Boris"> , <cfqueryparam cfsqltype="cf_sql_varchar" value="Huskic"> ) </cfquery>
Maybe, I could go wild and try something like this:
<cfquery name="test" datasource="#this.dsn#" result="testing"> <!--- DECLARE temp table ---> DECLARE @resultSet TABLE( no INT ) <!--- INSERT last current identity value into temp table ---> INSERT INTO @resultSet (no) VALUES (IDENT_CURRENT('contacts')); INSERT INTO contacts ( firstname ,lastname ) SELECT <cfqueryparam cfsqltype="cf_sql_varchar" value="Marko"> ,<cfqueryparam cfsqltype="cf_sql_varchar" value="Simic"> UNION ALL SELECT <cfqueryparam cfsqltype="cf_sql_varchar" value="Boris"> , <cfqueryparam cfsqltype="cf_sql_varchar" value="Huskic"> ; <!--- INSERT last inserted identity value into temp table ---> INSERT INTO @resultSet (no) VALUES (scope_identity()); <!--- SELECT and return values from temp table ---> SELECT * from @resultSet; </cfquery>
But that would be too nerdy :)





Post new comment