Get the number of columns in a query or structure in ColdFusion

Is there any method (preferably the absence of a loop) to get the number of columns as a result of a query? I am dealing with a module that uses a data set without knowing its details.

+4
source share
4 answers
<cfoutput> #ListLen(YourQuery.ColumnList)# </cfoutput> 
+14
source
 <cfquery name="myQuery" datasource="#dsn#"> SELECT * FROM myTable </cfquery> <cfoutput>#myQuery.columnList#</cfoutput> 
+1
source

For request:

 <cfquery name="qMyQuery" datasource="MyDatasource"> SELECT * FROM myTable </cfquery> <cfscript> cols = qMyQuery.columnList; colCount = ListLen(cols); </cfscript> 

For structure:

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

Based on either you can 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> 
0
source

In CF10 or Railo 4, you can use the Underscore.cfc size function with an array, query, object, or structure. 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, this is a good shorthand method. This is also useful when you want to get the size of a collection regardless of type.

Note. I wrote Underscore.cfc

0
source

Source: https://habr.com/ru/post/1344132/


All Articles