How can I perform a SQL SELECT with a LIKE condition for a string containing an open bracket character?

为君一笑 提交于 2019-12-10 16:56:37

问题


I have a simple search query:

<cfquery name="_qSearch" dbtype="Query">
    SELECT 
        *
    FROM    MyQoQ
    WHERE
        DESCRIPTION LIKE '%#URL.searchString#%'
</cfquery>

This query works excellently for most values. However, if someone searches for a value like "xxx[en", it bombs with the error message The pattern of the LIKE conditional is malformed..

Is there any way around this, since the bracket has a special use in CFQUERY?


回答1:


QoQ shares a feature of TSQL (MS SQL Server) whereby it's not just % and _ that are wildcards in LIKE - it also supports regex-style character classes, as in[a-z] for any lowercase letter.

To escape these values and match the literal equivalents, you can use a character class itself, i.e. [[] will match a literal [, and of course you probably also want to escape any % and _ in the user input - you can do all three like so:

'%#Url.SearchString.replaceAll('[\[%_]','[$0]')#%'

That is just a simple regex replace (using String.replaceAll) to match all instances of [ or % or _ and wrap each one in [..] - the $0 on the replacement side represents the matched text.



来源:https://stackoverflow.com/questions/21999686/how-can-i-perform-a-sql-select-with-a-like-condition-for-a-string-containing-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!