我正在使用 ColdFusion 并尝试创建一个函数,该函数允许我获取特定帐户中特定列的值(每个帐户都是它自己的记录/行)。
像这样的功能可以正常工作:
<cffunction name="getColumnValueFromAccount" access="public" returntype="string" >
<cfargument name="accountName" type="string" required="yes" />
<cfquery name="getColumn" datasource="mydatasource">
<!--- Note that the line below is 'hard-coded.' --->
SELECT role_ExampleSystem
FROM table_name
WHERE (accountName = <cfqueryparam cfsqltype="cf_sql_varchar" maxlength="50" value='#accountName#'>)
</cfquery>
<!--- It's easy to return the column value when you know what its name was. --->
<cfreturn getColumn.role_ExampleSystem >
</cffunction>
但我真正想要的是一个函数,它允许我指定从哪个列名读取,并且不需要制作一堆几乎相同的 CF 函数,它们只是具有不同的硬编码 SELECT 参数。我认为它应该看起来像这样,但是我在实际读取我认为它应该返回的单个字符串时遇到了麻烦。
<cffunction name="getColumnValueFromAccount" access="public" returntype="string" >
<cfargument name="accountName" type="string" required="yes" />
<!--- Trying to accept a column name as an argument --->
<cfargument name="columnName" type="string" required="yes" />
<cfquery name="getColumn" datasource="mydatasource">
<!--- I'm trying to use cfqueryparam to add specify the column name to select. --->
SELECT <cfqueryparam cfsqltype="cf_sql_varchar" maxlength="50" value='#columnName#'>
FROM table_name
WHERE (accountName = <cfqueryparam cfsqltype="cf_sql_varchar" maxlength="50" value='#accountName#'>)
</cfquery>
<!--- This line doesn't work. --->
<cfreturn getColumn[#columnName#] >
</cffunction>
我认为您可以在括号符号中使用变量,例如getColumn[#columnName#]
或者getColumn[columnName]
因为有人在评论中提到它。但是当我自己尝试使用变量时,它并没有按预期工作。我收到此错误:
The value returned from the getColumnValueFromAccount function is not of type string. If the component name is specified as a return type, it is possible that either a definition file for the component cannot be found or is not accessible.
知道当我想获得 cfquery 的单个结果时应该采取什么路线,但我没有在查询的 SELECT 部分使用硬编码的列名吗?通常这个过程很简单,但是当你的列名是一个变量时,情况似乎有点不同。