I have a table called dbo.Node:
NodeID int
ParentNodeID int
Title
The following functions shows the hierarchy
<cffunction name="getNodePath" returnType="string">
<cfargument name="NodeID" required="false" default="">
<cfset var qryNode = "">
<cfif NOT isNumeric(arguments.nodeID)>
<cfreturn "">
</cfif>
<cfquery name="qryNode" cachedWithin="#CreateTimeSpan(0,0,1,0)#">
SELECT ParentNodeID, Title
FROM dbo.Node WITH (NOLOCK)
WHERE NodeID = <cfqueryparam CFSQLType="CF_SQL_INTEGER" value="#arguments.NodeID#">
</cfquery>
<cfreturn getNodePath(qryNode.ParentNodeID) & qryNode.Title & " » ">
</cffunction>
This code uses cacheWithin because it is known that many of the same parent path will be called. On average this gets called about 20 times from the original page. Overall it gets called 100s of times because of the recursive nature of the query. Furthermore this function returns a string. This means the formatting is in the model not the view.
Is there a way to replace this with a CTE?
Version with CTE
The With statement replaces the recursive call. This function is now called only about 20 times. There is no need to cache the results because they will not get reused. The function now returns a query. The formatting is now on the view where it belongs