views:

1264

answers:

2

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.

+13  A: 

You can't get a row. You have to get a specific column.

<cfset x = QueryName.columnName[5]>
Patrick McElhaney
Thanks, thats what I was looking for.
Brian Bolton
I prefer bracket notation for both rows and columns, but either way is just as valid. QueryName["columnName"][5]. You'll need bracket notation if you want to use a variable for the column name, for instance.
Al Everett
A: 

you have to convert the query to a struct first,

<cfscript>
function GetQueryRow(query, rowNumber) {
var i = 0;
var rowData = StructNew();
var cols = ListToArray(query.columnList);
for (i = 1; i lte ArrayLen(cols); i = i + 1) {
rowData[cols[i]] = query[cols[i]][rowNumber];
}
return rowData;
}
</cfscript>

<cfoutput query="yourQuery">
<cfset theCurrentRow = GetQueryRow(yourQuery, currentRow)>
<cfdump var="#theCurrentRow#">
</cfoutput>

hope this points you in the right direction.

andrewWinn
i thought this was the only way to do this too, until i saw patrick's answer
Kip