我想创建一个动态查询以获取表数据。使用此动态查询,我们需要选择所有列或所需的列。需要动态加入,条件也要加入。
答案 0 :(得分:0)
我们可以在Coldfusion中创建一个动态SELECT查询。下面我添加了一个CFC函数,它具有动态查询。请检查一下。
<cffunction name="select" access="public" returntype="Query">
<cfargument name="tableName" type="string" required="true">
<cfargument name="joinType" type="array" required="false">
<cfargument name="conditionType" type="array" required="false">
<cfargument name="subQuery" type="array" required="false">
<cfargument name="orderBy" type="string" required="false">
<cfargument name="groupBy" type="string" required="false">
<cfargument name="neededColumns" type="string" required="false">
<cfquery name="selectQ">
SELECT
<cfif len(arguments.neededColumns)>
#arguments.neededColumns#
<cfelse>
*
</cfif>
<cfif structKeyExists(arguments, "subQuery")>
<cfloop array="#arguments.subQuery#" index="i">
,#PreserveSingleQuotes(i)#
</cfloop>
</cfif>
FROM
#arguments.tableName#
<cfif structKeyExists(arguments, "joinType") AND !ArrayIsEmpty(arguments.joinType)>
<cfloop array="#arguments.joinType#" index="i">
#i.type# JOIN #i.table# #i.alias# ON #i.primaryColumn# = #i.alias#.#i.secondaryColumn#
</cfloop>
</cfif>
WHERE 1=1
<cfif structKeyExists(arguments, "conditionType") AND !ArrayIsEmpty(arguments.conditionType)>
<cfloop array="#arguments.conditionType#" index="i">
AND #i.column#
<cfif structKeyExists(i, "symbol")>
#i.symbol#
<cfelse>
=
</cfif>
<cfif isNumeric(i.value)>
<cfqueryparam value="#i.value#" cfsqltype="cf_sql_numeric">
<cfelseif isDate(i.value)>
<cfqueryparam value="#i.value#" cfsqltype="cf_sql_timestamp">
<cfelse>
<cfqueryparam value="#i.value#" cfsqltype="cf_sql_varchar">
</cfif>
</cfloop>
</cfif>
<cfif structKeyExists(arguments, "groupBy") AND len(arguments.groupBy)>
GROUP BY #arguments.groupBy#
</cfif>
<cfif structKeyExists(arguments, "orderBy") AND len(arguments.orderBy)>
#arguments.orderBy#
</cfif>
</cfquery>
<cfreturn selectQ>
</cffunction>
下面的代码说明了如何调用上述函数以及如何将参数发送给该函数。
<cfset getAllDatas = application.base.get(
tableName = "Users U",
joinType = [
{"table" : "customers", "type" : "INNER", "alias" : "C", "primaryColumn" : "U.user_id" , "secondaryColumn" : "userid"},
{"table" : "customerType", "type" : "INNER", "alias" : "CT", "primaryColumn" : "C.eventid" , "secondaryColumn" : "eventid"}
],
subQuery = [
"(SELECT COUNT(*) FROM Participants WHERE UserID = #session.UserID# AND status = 'attended') AS count"
],
orderBy = " ORDER BY C.CreatedDate DESC",
groupBy = "C.CreatedDate",
conditionType = [
{ "column" : "UserID", "value" : session.userID},
{ "column" : "C.status", "value" : "Attended"}
]
)/>
伙计们,如果您有任何想法,请与我分享。
谢谢!