Cfloop: looping over a query

This question was posted in response to the following article: http://help.adobe.com/en_US/ColdFusion/10.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7 1a8.html

The getEmployees() method in example of dynamic references usage must be returns query (not string), right?

Similar Messages

  • Cfloop: looping over a date or time range

    This question was posted in response to the following article: http://help.adobe.com/en_US/ColdFusion/10.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7 1a9.html

    Currently the Attributes table says "1 day" is the default value for the 'index' attribute.  However, it is actually the default value for the 'step' attribute.  So the "1 day" should probably be moved from 'index' to 'step'.
    Thanks!,
    -Aaron

  • Looping over query by month

    etings,
    I have a query I am pulling that has a date field entitled, "Completed". I am attempting to loop over the query by date to slice and dice the data for a table and chart. Here is what I have done thus far...
    Setup two variables where I am only interested in the month. My plan is to fileter the date by month so I can pull the data out by month.
        <cfset startDate = #DatePart('m','01/01/09')#>
        <cfset endDate = #DatePart('m',Now())#>
    Here is my loop...
        <cfloop from = "#startDate#" to = "#endDate#" index = "i" step = "1">
    Here is one of my QoQs within the loop...
            <cfquery name="NPS0" dbtype="query">
            SELECT *
            FROM rsNPS
            WHERE #DatePart('m',rsNPS.completed)# = #i#
            </cfquery>
    I am having difficulties in getting this to work. Has anyone ever done something like this. I feel like the answer is right in front of me, but I have been staring at this code for a while. If anyone has any thoughts, I would be glad to hear them.
    ~Clay

    fs22 wrote:
             <cfquery name="NPS0" dbtype="query">
            SELECT *
            FROM rsNPS
            WHERE #DatePart('m',rsNPS.completed)# = #i#
            </cfquery>
    QoQ are a separate beast. You cannot use standard CF functions inside them.  AFAIK, QoQ only support a few functions like CAST, UPPER, LOWER, etcetera.  So as Dan suggested, you should peform the date functions in your database query.

  • Looping over a structure of arrays

    Hi Guys, I am trying to loop over a structure of simple
    arrays. The structure's second column contains a 1 dimentional
    array.
    I can't seem to get the proper syntax for my loop.

    I want to be able to dynamically loop over my query and
    decrypt it as I pass it into my structure. I have figured the code
    out to loop over the query and pass it to the structure. My problem
    now is whn I go to decrypt it I get this Error.
    There has been an error while trying to encrypt or decrypt
    your input string: Input length (with padding) not multiple of 16
    bytes.
    How can I fix this?
    Here is my code could it be because my varchar columns were
    not long enough. Here is my code.

  • Looping over QoQ Where Clause

    I have two queries. One is a main query that we pull from a form submission. The second is a small query resultset that lists different subgroups in my company and what main group they belong to. I pull several QoQ from the main query. In the main query results, there is a column that holds the subgroup information. I am trying to do a Q0Q where I group the data from the main query into the main groups for analysis. Here is an example...
    Main Query
    record 1 - subgroup 1
    record 2 - subgroup 2
    record 3 - subgroup 3
    Second Query
    Subgroup 1 - Main Group 1
    Subgroup 2 - Main Group 2
    Subgroup 3 - Main Group 1
    So I am trying to loop over a QoQ on the main query where the result set would contain the information only from Main Group 1. So record 2 would be eliminated. I have tried using an IN clause with a cfloop, but I run into syntax trouble with the comma. I also tried looping over the QoQ as a whole and the resulting dump is only the last record.
    If there is anything else you need, let me know.
    Any thoughts?
    Clay
    P.S. Here is a code sampling...
        <cfquery name="rsGroup" datasource="nps">
        SELECT *
        FROM "GROUP"
        WHERE GROUP.PrimaryGroup = '#form.primarygroup#'
        </cfquery>
        rsGroup - <cfdump var="#rsGroup#">
        <cfloop query="rsGroup" startrow="1" endrow="#rsGroup.RecordCount#">
            <cfquery name="rsGroupQoQ" dbtype="query">
            SELECT *
            FROM rsNPS
            WHERE rsNPS.grp = '#rsGroup.group#'
            </cfquery>
        </cfloop>
        rsGroupQoQ - <cfdump var="#rsGroupQoQ#"><cfabort>

    ok...I figured it out. I thought I would post my solution in case anyone else runs into this. Also, if anyone out there has a better way, let me know.
    <!---Dummy array to house 'blank' value for adding of column to main query--->
    <cfset GroupArray = ArrayNew(1)>
    <!---Variable that adds mainGroup column to main query with blank data from dummy array--->
    <cfset addMainGroup = QueryAddColumn(rsNPS,'mainGroup',GroupArray)>
    <!---Loop that sets value on added mainGroup column based off of main query grp column value--->
    <cfloop query="rsNPS" startrow="1" endrow="#rsNPS.RecordCount#">
        <cfif rsNPS.GRP EQ "xxxxx"><cfset rsNPS.mainGroup = "yyyyy"></cfif>
        <cfif rsNPS.GRP EQ "xxxxxxxxxx"><cfset rsNPS.mainGroup = "yyyyyyyyyy"></cfif>
        <cfif ...etc. ...
    </cfloop>

  • Looping over Nested Structure

    Hey Guys,
    I have a component that returns a structure. The structure is
    called ContactQuery. ContactQuery has to elements, one called
    Results, and one called Success. Results contains the data I want
    to loop over. If you try looping over the ContactQuery by using
    CFLoop and specify the ContactQuery as the collection, of course it
    only loops twice (once for Results, once for Success). How can I
    loop over the Results structure withing ContactQuery? You can see
    the dump of the structure at:
    http://www.digitalswordsmen.com/cfschedule/admin/Create_Tokens_Table.cfm
    Attached is the code I have. I am just unsure of the syntax
    for looping over the Results section of the structure.
    Thank you.

    Nope. I am dumb and didn't really think about it. The fact
    that it is a query nested in a structure threw me off. The code
    that works was
    <cfloop query="ContactQuery.Results">
    <tr>
    <td></td><td>#firstname#</td><td>#lastname#</td><td>#email#</td><td>#randrange(10000,9999 9)#</td>
    </tr>
    </cfloop>
    Thanks for the help, sorry about that dumb question.

  • Looping over cfdirectory

    Hello. I am having an issue with looping over cfdirectory.
    What I am trying to do here is grab the size of the files
    associated with the db. So where #current.Dir.Name# = #DB Column#
    update size etc.... What's happening is it is displaying the same
    id about 90 something times...Nice I know. Can anyone help?
    <cfloop query="qLoadFile">
    <cfoutput>
    <cfdirectory
    directory="/test1/test2/test3/0/#qLoadFile.owner_id#" action="list"
    name="currentDir">
    #qLoadFile.owner_id# <!--- This does display my ids
    correctly if I end the loop here but does not display anything in
    my table if I end the loop here and reopen it--->
    </cfoutput>
    <table border="1" bordercolor="#000000" >
    <tr>
    <td>File Name</td>
    <td>File Size</td>
    <td>Directory Location</td>
    <td>File Type</td>
    </tr>
    <cfloop query="currentDir">
    <tr>
    <cfoutput>
    <form name="updateSize" action="
    http://myURL.com/test2.cfm"
    method="post">
    <td><input type="text" name="name"
    value="#currentDir.Name#" /></td>
    <td><input type="text" name="size"
    value="#currentDir.Size#" /></td>
    <td>#right(currentDir.DIRECTORY, 2)#</td>
    <td>#currentDir.Type#</td>
    </cfoutput>
    </tr>
    </cfloop>
    </cfloop>
    </table> <br />
    <input type="text" name="number_of_directories"
    value="<cfoutput>#valuelist(qLoadFile.owner_id)#</cfoutput>">
    <input type="submit" name="submit" value="submit"/>
    </form>

    I just put your query into a random page of mine, changed the
    query to reflect a local database and got this output (all
    formatted correctly though!)
    Since I dont have the directory setup that you have the
    directory structures are empty, however it seems to be looping
    through fine
    59 File Name File Size Directory Location File Type
    60 File Name File Size Directory Location File Type
    61 File Name File Size Directory Location File Type
    62 File Name File Size Directory Location File Type
    63 File Name File Size Directory Location File Type
    64 File Name File Size Directory Location File Type
    65 File Name File Size Directory Location File Type
    Is this what you are looking for?

  • Loop over characters and numbers?

    Hi,
    I am working with a list of school grades.
    I have a query that returns a start value and and end value.
    Sometimes it may return, start_grade of 2 and end_grade of 5. I
    then loop over this using
    <cfloop from="#variables.start_grade#"
    to="#variables.end_grade#" index"i">
    </cfloop>
    The problem is sometimes "start_grade" is "P" for Preschool
    and "end_grade" is 8 for Eighth grade. I am wondering how I can
    loop over the grades in that scenario. It works fine when the grade
    is numeric, but when its a P or a K it does not work.
    Any help appreciated.
    -Westside

    I thought of that, but did not think -1 would be treated
    numerically for some reason. If that works, then my loop will be
    fine, but my display will not. When I want to output the grade, I
    will get a 0 or -1 as opposed to the user visually seeing P and a K
    So if I have a range of P - 4 for example
    I want to see in the display even though we have set them to
    0 and -1
    P, 1, 2, 3, 4
    If I do the conversion, when I am looping , I will lose the
    character representations that I need to display visually
    Any help apreciated.
    -Westside

  • Looping over cfset tag

    Hey Guys,
    I am having a problem with cfloop. What I am trying to do is
    calculate points on an Oline March Madness Pool. I need to evaluate
    if the user picks are equal to the game winners. I can do it if I
    manually type each pick # and each game # but I would much rather
    loop over a cfset tag since there are 63 picks and games. You can
    check out my code below to get a better idea of what I am trying to
    do. While I know I can't include the #'s on the right side of the
    cfset tag in this way I included them anyways to better illustrate
    where I would like to loop it. Is there a way to do this, or will I
    have to manually set each pick?

    <cfif getGames.game#l# EQ
    userPoints[#userID#]["pick#l#"]>
    I'm going to guess this is line 27 or very near it.
    Your actual <cfset> line looks fine to me assuming all
    the relevant keys
    exist when they need to exist. I would have written it
    something like:
    <cfset userPoints[userID]["pick" & i] =
    variables["pick" & i]>
    The if statement should probably look like this:
    <cfif getGames["game" & i] EQ
    userPoints[userID]["pick" & i]>
    All your index variables are the letter "i" and not the
    number "1"
    aren't they? I don't believe a singe number is a valid CF
    variable name.

  • Why optimizer prefers nested loop over hash join?

    What do I look for if I want to find out why the server prefers a nested loop over hash join?
    The server is 10.2.0.4.0.
    The query is:
    SELECT p.*
        FROM t1 p, t2 d
        WHERE d.emplid = p.id_psoft
          AND p.flag_processed = 'N'
          AND p.desc_pool = :b1
          AND NOT d.name LIKE '%DUPLICATE%'
          AND ROWNUM < 2tkprof output is:
    Production
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.01       0.00          0          0          4           0
    Execute      1      0.00       0.01          0          4          0           0
    Fetch        1    228.83     223.48          0    4264533          0           1
    total        3    228.84     223.50          0    4264537          4           1
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 108  (SANJEEV)
    Rows     Row Source Operation
          1  COUNT STOPKEY (cr=4264533 pr=0 pw=0 time=223484076 us)
          1   NESTED LOOPS  (cr=4264533 pr=0 pw=0 time=223484031 us)
      10401    TABLE ACCESS FULL T1 (cr=192 pr=0 pw=0 time=228969 us)
          1    TABLE ACCESS FULL T2 (cr=4264341 pr=0 pw=0 time=223182508 us)Development
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.01       0.00          0          0          0           0
    Execute      1      0.00       0.01          0          4          0           0
    Fetch        1      0.05       0.03          0        512          0           1
    total        3      0.06       0.06          0        516          0           1
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 113  (SANJEEV)
    Rows     Row Source Operation
          1  COUNT STOPKEY (cr=512 pr=0 pw=0 time=38876 us)
          1   HASH JOIN  (cr=512 pr=0 pw=0 time=38846 us)
         51    TABLE ACCESS FULL T2 (cr=492 pr=0 pw=0 time=30230 us)
        861    TABLE ACCESS FULL T1 (cr=20 pr=0 pw=0 time=2746 us)

    sanjeevchauhan wrote:
    What do I look for if I want to find out why the server prefers a nested loop over hash join?
    The server is 10.2.0.4.0.
    The query is:
    SELECT p.*
    FROM t1 p, t2 d
    WHERE d.emplid = p.id_psoft
    AND p.flag_processed = 'N'
    AND p.desc_pool = :b1
    AND NOT d.name LIKE '%DUPLICATE%'
    AND ROWNUM < 2
    You've got already some suggestions, but the most straightforward way is to run the unhinted statement in both environments and then force the join and access methods you would like to see using hints, in your case probably "USE_HASH(P D)" in your production environment and "FULL(P) FULL(D) USE_NL(P D)" in your development environment should be sufficient to see the costs and estimates returned by the optimizer when using the alternate access and join patterns.
    This give you a first indication why the optimizer thinks that the chosen access path seems to be cheaper than the obviously less efficient plan selected in production.
    As already mentioned by Hemant using bind variables complicates things a bit since EXPLAIN PLAN is not reliable due to bind variable peeking performed when executing the statement, but not when explaining.
    Since you're already on 10g you can get the actual execution plan used for all four variants using DBMS_XPLAN.DISPLAY_CURSOR which tells you more than the TKPROF output in the "Row Source Operation" section regarding the estimates and costs assigned.
    Of course the result of your whole exercise might be highly dependent on the actual bind variable value used.
    By the way, your statement is questionable in principle since you're querying for the first row of an indeterministic result set. It's not deterministic since you've defined no particular order so depending on the way Oracle executes the statement and the physical storage of your data this query might return different results on different runs.
    This is either an indication of a bad design (If the query is supposed to return exactly one row then you don't need the ROWNUM restriction) or an incorrect attempt of a Top 1 query which requires you to specify somehow an order, either by adding a ORDER BY to the statement and wrapping it into an inline view, or e.g. using some analytic functions that allow you specify a RANK by a defined ORDER.
    This is an example of how a deterministic Top N query could look like:
    SELECT
    FROM
    SELECT p.*
        FROM t1 p, t2 d
        WHERE d.emplid = p.id_psoft
          AND p.flag_processed = 'N'
          AND p.desc_pool = :b1
          AND NOT d.name LIKE '%DUPLICATE%'
    ORDER BY <order_criteria>
    WHERE ROWNUM <= 1;Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Loop Over Nested Structure

    Hello,
    Can someone please demonstrate how I would use a cfLoop to
    loop over and output the contents of this fictious nested
    structure?
    Thank You!

    mletson wrote:
    > I figured it out. If anyone has a better solution,
    please let me know.
    >
    > <cfloop from="1" to="#structCount(student)#"
    index="x">
    >
    > <cfset variables.studentID = "student00" & x>
    >
    > <tr>
    >
    <td><cfoutput>#student[studentID]["firstName"]#</cfoutput></td>
    >
    <td><cfoutput>#student[studentID]["lastName"]#</cfoutput></td>
    >
    <td><cfoutput>#student[studentID]["phone"]#</cfoutput></td>
    > </tr>
    >
    > </cfloop>
    >
    A slightly simpler version using the structure form of the
    <cfloop...>
    tag. It also demonstrates both array notation, that you used,
    as well
    as dot notation. Finally it puts a single <cfoutput...>
    block around
    the entire loop. This can provide a small but accumulative
    performance
    improvement.
    <cfoutput>
    <cfloop collection="#student#" item="aStudent">
    <tr>
    <td>#aStudent["firstName"]# OR
    #aStudent.firstName#</td>
    <td>#aStudent["lastName"]# OR
    #aStudent.lastName#</td>
    <td>#aStudent["phone"]# OR #aStudent.phone#</td>
    </tr>
    </cfloop>
    </cfoutput>

  • Looping Over INSERT

    I've got a form. The form asks the visitor their address
    (first name, last name, street address, apartment number, city,
    state, and zip code... each a separate text field). This form is
    repeated 10 times on the page, allowing the visitor to enter
    multiple addresses. I've given each form field a unique name by
    just appending "_1" or "_2" after it. For example, my fields are
    named...
    FIRST FORM BLOCK
    first_name_1
    last_name_1
    SECOND FORM BLOCK
    first_name_2
    last_name_2
    Each form block (address) will be inserted into a table in my
    database as a new row. Is there a quick and easy way to loop over
    the insert 10 times, rather than have 10 separate INSERT statements
    in my code? A CFLOOP would work just fine if not for dynamic form
    field names, but I would have to take into account the "_X". I want
    to say I've done this before; I'm just overthinking.

    <cfloop from="1" to="10" index="i">
    <cfquery ...>
    INSERT INTO ...
    (aCol,bCol,cCol...)
    <!--- The important part, accessing the form structure
    with array
    notation --->
    #form['first_Name_' & i]#,
    #form['last_Name_' & i]#
    </cfquery>
    </cfloop>
    The array notation for a complex variables is a very powerful
    concept.
    Many advance techniques can be used with it.

  • Loop over form values & insert into db

    Form
    prod_id     prod_name       prod_price    prod_status
    001         product 001     1.00          1            
    002         product 002     2.00          1      
    003         product 003     3.00          0      
    004         product 004     4.00          0      
    Form Dump
    prod_name      product 001,product 002,product 003,product 004
    FIELDNAMES     prod_id, prod_name, prod_price, prod_status
    prod_price     1.00,2.00,3.00,4.00
    prod_status    1,1,0,0
    prod_id        001,002,003
    I want to update a few fields, prod_price and prod_status. I submit these values to my update page but I'm not sure how to loop over these values and update by the prod_id. In my update page I'm using cfdump and I see the structure of the form, the fieldnames as well as the prod_id, prod_name, etc and their values.
    My question is how do I loop over these form values so I'll be able to update by each prod_id? I've played around with looping over the form collection values but no luck.

    When I do stuff like this, I append the "id" value to the end of each form field.  That enables me to ensure the other fields match up.
    When processing the form, I generally do something like this:
    <cfloop list="#form.fieldnames# index="ThisField">
    <cfif left(ThisField, 9) is "prod_name">
    <cfscript>
    ThisID = removechars(thisfield, 9);
    ThisName = form["prod_name" & ThisID];
    same for other fields
    Then do something with those variables.

  • Error when looping over list

    Looping over a series of lists created from form fields
    generates an error when one of the fields on the form has been left
    blank. The form is a list of event dates, start times and end
    times. One event can have a number of times.
    When the end time is uncertain, we want to leave it blank.
    However, doing so shortens the list created from #form.endtime# so
    that the lists don't match and there's an error message:
    "Invalid list index 2.
    In function ListGetAt(list, index [, delimiters]), the value
    of index, 2, is not a valid as the first argument (this list has 1
    elements). Valid indexes are in the range 1 through the number of
    elements in the list."
    How do you get around this problem? Tx.

    yoman,
    No need for separate forms. Use a counter to number each
    group of field names
    <input name="EventDateID1" ...>
    <input name="EventDate1" ...>
    <input name="EventDateID2" ...>
    <input name="EventDate2" ...>
    Then loop through the form fields on your action page
    <cfloop from="1" to="#form.maxCounter#"
    index="counter">
    <cfset EventDateID = form["EventDateID#counter#">
    <cfset EventDate = form["EventDate#counter#">
    ... rest of fields
    <cfquery name="UpdateFeatures" datasource="#dsn#">
    UPDATE EventDates
    SET EventDate = '#EventDate#', ....
    WHERE EventDateID = #EventDateID#
    </cfquery>
    </cfloop>
    You should validate the values and/or use cfqueryparam

  • Looping over a structure

    How do I loop over this structure to populate it with a Query
    Recordset?
    <cfset myStruct =
    objImage.getSize("images/products/largeImages/#Recordset1.elink#")>
    I really appreciate your help.

    I would like to populate the structure with the image file
    names that are coming from the query. The structure is built from a
    java object. Here is the function to create it.
    <cfcomponent>
    <cffunction name="getSize" returntype="struct"
    access="public" output="No">
    <cfargument name="Image" required="Yes" type="string">
    <cfset myImage = createObject("java",
    "javax.swing.ImageIcon")>
    <cfset myImage.init(expandpath(arguments.Image))>
    <cfset myStruct = StructNew()>
    <cfset myStruct.width = myImage.getIconWidth()>
    <cfset myStruct.height = myImage.getIconHeight()>
    <cfreturn myStruct>
    </cffunction>
    </cfcomponent>
    <cfobject component="imageSize" name="objImage">
    <cfset myStruct =
    objImage.getSize("/images/someimage.jpg")>
    <cfoutput>
    width: #myStruct.width#
    height: #myStruct.height#
    </cfoutput>
    Right now the structure only gives me the first row of the
    query. I have tried using the cfquery loop to populate the
    structure with now results. I suspect I am using the wrong
    syntac.

Maybe you are looking for