sql-server-2005 - mssql 另一种使用 IN 编写查询的方法?

标签 sql-server-2005 coldfusion

我正在更新网页搜索表单。用户选择他们想要搜索的组名称。在操作页面上,为了简单起见,我最终得到以下查询:

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/

相关文章:

c# - 与 SQL Server 一起使用时如何定期刷新 dapper.net 缓存

sql-server - SQL Server 2005 的测试优先开发工具?

jquery - 需要帮助使用 ColdFusion 和 jsTree 复制目录结构

javascript - 将 HTML Collection 中的值存储在数组中?

javascript - 如何强制 Coldfusion cfc 将 JSON 上的数字数据作为字符串输出?

coldfusion - 尽管“启用空支持”已关闭,但在 cf2018 中启用了空

java - 我与数据库的 JDBC 连接是否使用 SSL?

sql - 什么是更快的查询(选择名称....或选择顶部(1)名称

sql - 插入 id(自动生成,仅列)

coldfusion - 在 Coldfusion/Lucee 中尝试/捕捉/ throw /最终/重新 throw