开发者

Get number of columns in a query or structure in ColdFusion

Is there any expedient (preferably no l开发者_开发百科oop) way to get the number of columns in a query result? I'm dealing with a module that uses a data set without knowing its details.


<cfoutput>
   #ListLen(YourQuery.ColumnList)#
</cfoutput>


<cfquery name="myQuery" datasource="#dsn#">
SELECT * FROM myTable
</cfquery>

<cfoutput>#myQuery.columnList#</cfoutput>


For a Query:

<cfquery name="qMyQuery" datasource="MyDatasource">
  SELECT *
  FROM myTable
</cfquery>

<cfscript>
  cols = qMyQuery.columnList;
  colCount = ListLen(cols);
</cfscript>

For a Structure:

<cfset stStruct = {
  key1="Value1",
  key2="Value2",
  key3="Value3"
} />
<cfscript>
  cols = structKeyList(stStruct);
  colCount = structCount(stStruct);
</cfscript>

Based on either you can then do something like this:

<table>
  <thead>
    <tr>
      <cfloop list="#cols#" delimiters="," index="c"><th>#c#</th></cfloop>
    </tr>
  </thead>
  <tbody>
<!-- for structure -->
    <tr>
      <cfloop list="#cols#" delimiters="," index="c"><td>#stStruct[c]#</td></cfloop>
    </tr>
<!-- for query -->
    <cfoutput query="qMyQuery">
    <tr>
      <cfloop list="#cols#" delimiters="," index="c"><td>#qMyQuery[c][qMyQuery.currentRow]#</td></cfloop>
    </tr>
    </cfoutput>
  </tbody>
</table>


In CF10 or Railo 4, you can use Underscore.cfc's size function with an array, query, object or struct. Examples:

_ = new Underscore();// instantiate the library

_.size([1, 2, 3]);// returns number of elements (3)
_.size(query);// returns number of rows
_.size(object);// returns number of keys
_.size({a: 1, b: 2});// returns number of keys (2)

Although it simply delegates to native arrayLen() for arrays, structCount()for structs/objects, and recordCount for queries, it is a nice shorthand method. It is also useful when you want to be able to get the size of a collection regardless of the type.

Note: I wrote Underscore.cfc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜