Some of us are fans of using CFSCRIPT for certain portions of our code. For myself, I’ll typically create my UDFs (User Defined Functions) in this manner…it just looks cleaner to my eye. There can be challenges to doing this, however, due to the fact that certain commonly used CF tags just do not have equivalent CFSCRIPT function calls, like CFQUERY or CFTHROW. It is, however, still possible to incorporate them.
I think a code sample is worth a thousand words, so consider the following sample:
<!--- first, we need to turn the CFQUERY tag into a coldfusion function --->
<cffunction name="cfquery" access="public" returntype="query">
<cfargument name="dsn" type="string" required="true">
<cfargument name="sqlstring" type="string" required="true">
<cfargument name="password" type="string" required="false" default="">
<cfargument name="username" type="string" required="false" default="">
<cfif arguments.username IS NOT "" and arguments.password IS NOT "">
<cfquery
name="thisquery"
datasource="#arguments.dsn#"
username="#arguments.username#"
password="#arguments.password#">
#arguments.sqlstring#
</cfquery>
<cfelse>
<cfquery name="thisquery" datasource="#arguments.dsn#">
#preservesinglequotes(arguments.sqlstring)#
</cfquery>
</cfif>
<cfreturn thisquery>
</cffunction>
<!--- begin the actual UDFs --->
<CFSCRIPT>
function getProdDescrip(productid){
var thisSQL = "select shortdescrip from products where baseid ='" & productid & "'";
descrip = cfquery(dsn="rrtradingpost",sqlstring=thisSQL);
return descrip.shortdescrip;
}
</CFSCRIPT>
<!--- end UDFs --->
<cfset thisDescrip = getProdDescrip('BCPLB')>
<cfoutput>#thisDescrip#</cfoutput>
Step 1 is to turn any needed CF tags into functions using the CFFUNCTION tag, defining the tag’s attributes as arguments to the CFFUNCTION.
Then, within our CFSCRIPT section we can refer to the newly created function by name, passing in the pertinent arguments. That’s it!
One thing to consider with this is that you can't build a sql string that includes the cfqueryparam tag and have it work, so you'll have to compromise on this and just pass in your where clause values in native sql format (single quotes, etc.).
Keep it beautiful. Doug out.
You are not logged in, so your subscription status for this entry is unknown. You can login or register here.