Counting Records

SQL Chores Add comments

This is pretty trivial, and I know that ORM probably handles everything better these CF9 days (I haven't really jumped into that ORM thing yet) but I make a CFC for just about every table I work with and sometimes I just want to know how many of a particular thing there is in the table.  Here's a function I include in all of my CFCs for that.

<cffunction name="countRecords" returnType="Numeric" output="false">

<cfargument name="sqlWhere" required="no">
<cfparam name="sqlWhere" default="thingID > 0">

<cfquery 
	datasource 			="#request.thisDSN#"
	name 						="countAll"
	>
	SELECT COUNT(thingID) as ttlRecords
	FROM things
	WHERE #PreserveSingleQuotes(sqlWhere)#
</cfquery>

<cfset ttlRecords = #countAll.ttlRecords[1]#>

<cfreturn #ttlRecords#>

</cffunction>

That lets me do a quick invoke that wastes little time or bits and just gives me a number back. I can even pass a little SQL along with the request to get counts on specific things.

0 responses to “Counting Records”

Leave a Reply

Leave this field empty:

Powered by Mango Blog. Initial Template Design and Icons by N.Design Studio, modified by Michael Cummins.