Wednesday, July 22, 2009

Number of Rows Updated with MSSQL

Sometime I want to know how many rows were updated when I update the database in Coldfusion using Microsoft Database Server but a normal query doesn't have that information. What I need to do is use the NOCOUNT setting. In the following example I also create a variable to record all of the rows updated with multiple update statements generated in a cfloop:


<cfquery name="qryUpdateTable" datasource="#Datasource#">
SET NOCOUNT ON
DECLARE @rowsUpdated AS INT
SET @rowsUpdated = 0
<cfloop list="#FORM.List#" index="thisListItem" >
UPDATE TableToUpdate SET
Col1 = <cfqueryparam cfsqltype="cf_sql_integer" value="#FORM['Col1_#thisListItem#']#" />,
Col2 = <cfqueryparam cfsqltype="cf_sql_bit" value="#FORM['Col2_#thisListItem#']#" />
WHERE TableToUpdateID = <cfqueryparam cfsqltype="cf_sql_integer" value="#thisListItem#" />
SET @rowsUpdated = @rowsUpdated + @@ROWCOUNT
</cfloop>
SELECT @rowsUpdated AS rowsUpdated
SET NOCOUNT OFF
</cfquery>
<cfif qryUpdateTable.rowsUpdated>
<span style="color: green">SUCCESS</span> : <cfoutput>#qryUpdateTable.rowsUpdated#</cfoutput> Rows Updated
</cfif>

No comments:

Post a Comment