Question

I am trying to set a variable dynamically into a structure via CFLOOP. I have read Ben Nadal's blog post but cant seem to get the assignment correct. I would like to use dot notation and make the VIN a sub structure of values.

Here is my code:

<cfloop query="VINs">
    <cfquery name="carsQue" datasource="carsData">
      SELECT VIN, MODEL, MAKE, etc
      FROM CarsDB
      WHERE (VIN = #VIN#)
    </cfquery>

     <cfset carsStruct= StructNew()>
     <cfset carsStruct.[VIN].MAKE = '#carsQue.MODEL#'>
     <cfset carsStruct.[VIN].MODEL = '#carsQue.MAKE#'>
</cfloop>

Any guidance would be greatly appreciated,

Thanks

Was it helpful?

Solution

Running a query inside a loop is almost always a bad idea. In your case, a better option would be:

<cfif ListLen(valuelist(vins.vin)) gt 0>
<cfquery name=CarsQue datasource = "carsData">
select vin, model, make, etc
from carsDB
where vin in (<cfqueryparam cfsqltype="cf_sql_varchar"
value="#valuelist(vins.vin)#" list="true">)
</cfquery>

<cfset carsStruct = StructNew()>

<cfloop query="carsQue">
code for your struct
</cfloop>

<cfelse>
code for vins query returning no data
</cfif>

Better yet would be to get all the data with one query. You didn't provide enough information to determine if this was possible, but it often is.

OTHER TIPS

Create a structure outside loop and and setting variable within loop can solve the problem. in a current scenario each time loop run its create a new structure.

you can do some thing like this

 <cfset carsStruct= StructNew()>
 <cfloop query="VINs">
   <cfquery name="carsQue" datasource="carsData">
   SELECT VIN, MODEL, MAKE, etc
   FROM CarsDB
   WHERE VIN = <cfqueryparam cf_sql_type="cf_sql_varchar" value="#VINs.VIN#">
   </cfquery>

   <cfset carsStruct[VINs.VIN].MAKE = carsQue.MODEL>
   <cfset carsStruct[VINs.VIN].MODEL = carsQue.MAKE>
 </cfloop>

Based on the limited information you've given you should be able to run one query and loop through that to add to your struct.

<cfset carsStruct= {}> //new struct
<cfif VINs.RecordCount> //your VINs query has records
  <cfquery name="carsQueue" datasource="carsData">
  SELECT VIN, MODEL, MAKE, etc
  FROM CarsDB
  // Quoted list of all your VINs. cfqueryparam prevents against SQL injection 
  WHERE VIN IN (<cfqueryparam cf_sql_type="cf_sql_varchar" value="#ValueList(VINs.VIN)#" list="true">
  </cfquery>


  <cfloop query="carsQueue">
    <cfset carsStruct.[carsQueue.VIN].MAKE = carsQueue.MODEL>
    <cfset carsStruct.[carsQueue.VIN].MODEL = carsQueue.MAKE>
  </cfloop>
<cfelse>
   // if VINs query return nothing a blank struct will be returned.
   //You do NOT need this <cfelse> unless you are returning something when the query is blank
</cfif>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top