2011-11-16 262 views
2

我是coldfusion的新手,我在循環查詢函數中遇到困難。例如,我有一個函數,其中有一個查詢返回以'a'開頭的名稱。但我能從數據庫中只獲得一個值(第一個值)。實際上,在db中,我們有超過1個值的查詢。我應該如何在函數中循環查詢? 任何幫助表示讚賞...預先顯示查詢結果

<cffunction name="getNames" returntype="any"> 
<cfargument name="letter" required="true"> 
<cfquery name="getNamesfrmDB" datasource="test"> 
select * from employee where firstname like '#arguments.letter#%' 
</cfquery> 

<cfreturn getNamesfrmDB/> 
</cffunction> 
<cfoutput>#getNames('a').firstname#</cfoutput> 

謝謝...

+0

''

使用query = 「qname的」 將只返回第一行。正如Jason所說的,將查詢屬性添加到標記以循環記錄集。 –

回答

2

啊。我準備好你的問題了......忽略以前的答案。

你正在將查詢直接傳遞給函數,所以它會作爲查詢出現,你可以將它當作查詢來處理。在cfouptut

<cffunction name="getNames" returntype="any"> 
     <cfargument name="letter" required="true"> 
     ... your query .. 
     <cfreturn getNamesfrmDB/> 
    </cffunction> 

    <!---call the function---> 
    <cfset names = getNames('a')> 

    <!---now loop over the results using cfoutput---> 
    <cfoutput query="names"> 
     <p>#firstname#</p> 
    </cfoutput> 

    <!---OR ALTERNATIVELY, as you can't use cfoutput inside cfoutput.. so if you are already inside a cfouput, you can also output query results using cfloop---> 
    <cfoutput> 
     ..some other stuff... 
     <cfloop query="names"> 
      <p>#firstname#</p> 
     </cfloop> 
     ..some other stuff.. 
    </cfoutput>