I want to get a specific row in a ColdFusion Query object without looping over it.
I'd like to do something like this:
<cfquery name="QueryName" datasource="ds">
SELECT *
FROM tablename
</cfquery>
<cfset x = QueryName[5]>
But it's giving me an error saying that the query isn't indexable by "5". I know for a fact that there are more than 5 records in this query.
You have to convert the query to a struct first:
Hope this points you in the right direction.
I wanted to extract a single row from a query, and keeping the column names (of course). This is how I solved it:
This can now be accomplished in coldfusion 11 via QueryGetRow
I know I come back to this thread any time I Google "cfquery bracket notation". Here's a function I wrote to handle this case using bracket notation. Hopefully this can help someone else too:
The REReplace is optional, I have it in there to cleanse commas so that it doesn't screw up the arrayToList function later on if you have to use it.
You can't get a row in CF <= 10. You have to get a specific column.
It's been 8 years since I posted this answer, however. Apparently CF11 finally implemented that feature. See FrankieZ's answer.
Methods previously described for obtaining query data by column name and row number (variables.myquery["columnName"][rowNumber]) are correct, but not convenient for getting a full row of query data.
I'm running Railo 4.1. And this is a cool solution. Too bad this can't be done the way we would want outright to get a full row of data, but the following method allows us to get what we want through a few hoops.
When you
serializeJSON(variables.myquery)
it changes the query to a JSON formatted cfml struct object with two items: "Columns" and "Data". Both of these are arrays of data. The "data" array is a two-dimensional array for rows and then columnar data.The issue is that now we have an unusable string. Then if we re-serialize it it's NOT a query, but rather usable regular struct in the format described above.
Assume we already have a query variable named 'variables.myquery'. Then look at the following code:
Now you get the two dimensional array by getting this:
And you get one query row array by getting this:
OR the last row this way:
And you can get individual column values by column order number iteration:
Now this might be slow and possibly unwise with large query results, but this is a cool solution nonetheless.