我正在更新网页搜索表单。用户选择他们想要搜索的组名称。在操作页面上,为了简单起见,我最终得到以下查询:
select GroupName
from groupTable
where groupName in ('Motley Crue','Alvin and the Chipmunks')
通常情况下,这对我来说不是问题,但在这种情况下,数据库字段还可能包含一串名称,例如:
Big Dog's Chair,Purple Dragon,Just Johnny,Johnny Faster,Van Halen
我相信我必须循环遍历数据库字段中的每个项目和逗号分隔列表中的每个项目。如果是这样的话,我不知道该怎么做,也不知道在 SO 或 google 中使用什么搜索词。我需要一些帮助。
数据库:MSSQL 2005 冷聚变:CF9
我于 5:00 CST 下类,所以如果您回复,我可能要到明天才能看到。
最佳答案
马特走在正确的道路上,但是:
如果组名称是组的子字符串,该解决方案可能会产生意外结果。例如,假设用户选择了“粉色”。该查询还将匹配“Pink Floyd”或“Big Pink”或任何其他包含 Pink 的乐队。
我假设您的表单变量的名称是“selectedGroups”。将其更改为实际的内容并且它应该可以工作。
select
groupName
from
groupTable
where
<!--- I thought I knew a more graceful way of doing this but it isn't coming to me --->
<cfloop list = '#form.selectedGroups#' index = "i">
groupName = '#i#' <!--- match the group if the column only contains one value --->
or groupName like '#i#,%' <!--- match the group if it is the first group in the list --->
or groupName like '%,#i#,%' <!--- match the group name if it is in the middle of the list --->
or groupName like '%,#i#' <!--- match the group name if it is the last group in the list --->
#i neq listLast(form.selectedGroups) ? ' or ' : ''# <!--- add an or for the next value to search --->
</cfloop>
关于sql-server-2005 - mssql 另一种使用 IN 编写查询的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13148003/