HOME | FERGUSON Digital Blog

Return Multiple Calculations From Single UDF

ColdFusion Add comments

I was recently working with a need to compare two results from a single User Defined Function (UDF). On the surface, this is impossible since a function can only return one result. However, that limitation can be overcome if that result is a structure of all the results given in a set of calculations.

In the example below, I've really simplified a function into something that you wouldn't necessarily bother to return as a structure, but this is just to help get a down and dirty idea across without getting bogged down in a complex UDF.

Here we are trying to determine what the last day of the current month is and how many days until that date.

<cffunction name="fnMonthLastDay" access="public" returntype="struct">
   <cfargument name="SetDate" type="string" required="yes">
   <cfscript>
      var SetYear=DatePart("yyyy", SetDate);
      var SetMonth=DatePart("m", SetDate);
      if (ArrayLen(Arguments) GT 1)
      SetYear=Arguments[2];

      LastDay=StructNew();
      LastDay.LastDate=DateAdd("d", -1, DateAdd("M", 1, CreateDate(SetYear, SetMonth, 1)));
      LastDay.LastDays=DateDiff("d", Now(), LastDay.LastDate);

      return LastDay;
   </cfscript>
</cffunction>

<cfset LastDay=fnMonthLastDay(Now())>
<cfdump var="#LastDay#">

The UDF grabs the year and month from the date value passed, advances it to the first of the following month, then subtracts one day from it to determine the last day. Then the UDF calculates the difference between the two dates and returns a structure. We set the result against a variable, in case we want to use it more than once and end by dumping the structure LastDay with two elements (LastDate, and LastDays).

If you find this post useful please leave a comment and let me know how you used the information.

0 responses to “Return Multiple Calculations From Single UDF”

Leave a Reply




© Copyright 1997-2024, All Rights Reserved Coldfusion and MS SQL2008
Powered by Mango Blog.   Design by FERGUSON Digital
o:Event name="beforeHtmlBodyEnd" />