3

我有一个查询查询,它对变量字符串执行 LIKE 条件:

当变量包含一个包含单引号的单词时,会返回一些结果,但不是全部:

<cfset _myVar = "Women's" />

<cfquery name="_qData" dbtype="Query">
    SELECT 
        ID
    FROM   MyQoQ
    WHERE  NAME LIKE '%#_myvar#%'
        OR DESCRIPTION LIKE '%#_myvar#%'
</cfquery>

如果变量包含多个单词,并且其中一个单词包含单引号,则不返回任何记录:

<cfset _myVar = "Women's Initiative" />

<cfquery name="_qData" dbtype="Query">
    SELECT 
        ID
    FROM   MyQoQ
    WHERE  NAME LIKE '%#_myvar#%'
        OR DESCRIPTION LIKE '%#_myvar#%'
</cfquery>

我已经尝试过PreserveSingleQuotes()用 包装变量CFQUERYPARAM,但是无济于事 - 我得到了相同的结果。

有没有办法使这项工作?


添加一个复制案例

<cfset myQuery = queryNew('hello')>
<cfset queryAddRow(myQuery,5)>
<cfset querySetCell(myQuery,"hello","what up",1)>
<cfset querySetCell(myQuery,"hello","what's up",2)>
<cfset querySetCell(myQuery,"hello","what's up friends",3)>
<cfset querySetCell(myQuery,"hello","what u",4)>
<cfset querySetCell(myQuery,"hello","what",5)>
<cfdump var="#myQuery#">

<cfquery name="res" dbtype="query">
SELECT *
FROM myQuery
WHERE hello LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="%$what's up%">
</cfquery>

<cfdump var="#res#">

Railo 4.1.1.009 - 返回两个结果(第 2 行和第 3 行) ColdFusion 10,0,13,287689 - 如果我将 SQL 更改为

WHERE hello LIKE '%what''s up%'

我仍然没有结果

4

2 回答 2

1

我正在运行 ColdFusion 10 u13。

修改你的回购代码这似乎工作:

<cfset myQuery = queryNew('hello')>
<cfset queryAddRow(myQuery,5)>
<cfset querySetCell(myQuery,"hello","what up",1)>
<cfset querySetCell(myQuery,"hello","what's up",2)>
<cfset querySetCell(myQuery,"hello","what's up friends",3)>
<cfset querySetCell(myQuery,"hello","what u",4)>
<cfset querySetCell(myQuery,"hello","what",5)>
<cfdump var="#myQuery#">

<cfquery name="res" dbtype="query">
SELECT *
FROM [myQuery]
WHERE [hello] LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="%what''s up%">
</cfquery>

请注意 <cfqueryparam> 标记中的双单引号。像 Dan 一样,我会认为 <cfqueryparam> 标记会自动为您解决这个问题。也许这是 QoQ 中的错误?

于 2014-03-18T07:11:54.457 回答
1

啊!!皇室痛苦的经典案例。

为了解决这个问题,您必须在搜索词中的每个 ' 中添加一个额外的 ',然后将其转义。

<cfset myQuery = queryNew('hello')>
<cfset queryAddRow(myQuery,5)>
<cfset querySetCell(myQuery,"hello","what up",1)>
<cfset querySetCell(myQuery,"hello","what's up",2)>
<cfset querySetCell(myQuery,"hello","what's up friends",3)>
<cfset querySetCell(myQuery,"hello","what u",4)>
<cfset querySetCell(myQuery,"hello","what",5)>
<cfdump var="#myQuery#">

<cfset  x = "what's up" />

<cfquery name="res" dbtype="query">
SELECT *
FROM myQuery
WHERE hello LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="#replace(x, "'", "''", "all")#%">
</cfquery>

<cfdump var="#res#">

如果你直接这样做,正如你提到的,

WHERE hello LIKE '%what''s up%'

解析器正在发疯。但是,如果您通过函数返回值传递值,则通过变量的运行时赋值会以某种方式使解析器感到高兴。

我记得在发送多个用';'分隔的SQL语句时使用了这样的技巧 在cfquery中。直接写

"DECLARE x NUMBER; SELECT 2 INTO x FROM DUAL;" 

cfquery 内部失败,但将它们分配给一个字符串,然后将字符串作为任何字符串操纵器函数(lcase、ucase 等)的返回值发送,效果很好。

注意:问题已解决,但如果我的解释和方法有差异,请随时纠正和评论。

于 2014-03-18T06:23:41.810 回答