Skip to main content
Inspiring
December 22, 2011
Question

loop inside query

  • December 22, 2011
  • 1 reply
  • 1118 views

Hi all,

I need to select some fields from three queries.

Can I do a loop inside query of queries?

Here is my code:

<cfquery dbtype="query" name="qryData" >

                select my_ID, my_DESC

                 <cfloop from="1" to="#totalYears#" index="y">

                     ,year_#y#

                 </cfloop>

                from queryA

                union all

                select my_ID, my_DESC

                 <cfloop from="1" to="#totalYears#" index="y">

                     ,year_#y#

                 </cfloop>

                from queryB

                union all

                select my_ID, my_DESC

                 <cfloop from="1" to="#totalYears#" index="y">

                     ,year_#y#

                 </cfloop>

                from queryC

            </cfquery>

Maybe is a better way to do this.

Thanks!

    This topic has been closed for replies.

    1 reply

    Inspiring
    December 22, 2011

    What happened when you tried?

    jfb00Author
    Inspiring
    December 23, 2011

    Hi,

    Thanks for you reply.

    I am getting an error: coldfusion.runtime.Struct cannot be cast to coldfusion.sql.QueryTable

    If I hard code the years fields, it works fine.

    Any ideas?

    Thanks

    Inspiring
    December 23, 2011

    If the code you posted is your actual code, what that error message is saying is that one of queryA, queryB or queryC is a struct, not a query.

    Along with the error message which tells you what the problem is, CF will also be telling you an approximate line number that it's occurring.  That's usually a good pointer as to what the problem is and where it lies.

    Incidentally, you can simplify your code somewhat by just capturing the output from the loop once, and then reusing that value the subsequent times, rather than repeating the same logic three times.

    --
    Adam