在使用LIKE运算符的可选参数查询中,Escape特殊字符无法正常工作。 这是查询的一部分
NAME LIKE CASE WHEN '%'+@Name+'%' IS NULL THEN NAME ELSE '%'+@Name+'%' END
我以为我可以像
那样NAME LIKE CASE WHEN '%'+@Name+'%'ESCAPE '\' IS NULL THEN NAME ELSE '%'+@Name+'%' END
但是当我添加转义'\'但它引发了错误。 任何帮助??
演示代码:
set @Name='Restaur\[ant'
SELECT [JOB].HOUSE_CODE, [JOB].JOB_CODE, [JOB].OPEN_DATE, [JOB].NAME AS Position, [JOB].DESCRIPTION, [RESTAURANT].ZIP_CODE AS ZipCode,
[STATE].STATE_NAME AS State, [RESTAURANT].CITY_NAME AS City
FROM [JOB] INNER JOIN
[RESTAURANT] ON [JOB].HOUSE_CODE = [RESTAURANT].HOUSE_CODE INNER JOIN
[STATE] ON [RESTAURANT].STATE_CODE = [STATE].STATE_CODE INNER JOIN
[JOB_CODE] ON [JOB].HOUSE_CODE = [JOB_CODE].HOUSE_CODE AND [JOB].JOB_CODE = [JOB_CODE].JOB_CODE AND
[RESTAURANT].HOUSE_CODE = [JOB_CODE].HOUSE_CODE
WHERE ( [JOB].NAME LIKE CASE WHEN '%'+@Name+'%' IS NULL THEN [JOB].NAME ELSE '%'+@Name+'%' END ESCAPE '\' )
答案 0 :(得分:5)
将ESCAPE放在CASE语句之外。此外,仅测试@Name为NULL就足够了。
NAME LIKE CASE WHEN @Name IS NULL THEN NAME ELSE '%'+@Name+'%' END ESCAPE `\`
编辑:这里有一些演示代码来说明这项技术。
declare @test table (
name varchar(100)
)
insert into @test
(name)
select 'I am 100% confident this works.' union all
select 'There can be no doubt.' union all
select 'I would like to eat in fine restaur[ant some day.'
declare @name varchar(100)
/* Case when @name is NULL */
select name
from @test
where name like case when @name is null then name else '%'+@name+'%' end escape '\'
set @name = '100\%'
/* Case when @name has a value with a % */
select name
from @test
where name like case when @name is null then name else '%'+@name+'%' end escape '\'
set @name = 'restaur\[ant'
/* Case when @name has a value with a [ */
select name
from @test
where name like case when @name is null then name else '%'+@name+'%' end escape '\'
答案 1 :(得分:1)
您是否尝试在ESCAPE
之前添加空格?
+'%'ESCAPE '\' IS
到此:
+'%' ESCAPE '\' IS
答案 2 :(得分:0)
你在找什么?我尝试了你的第一个例子,它表现得像我期望的那样:
CREATE TABLE test2 (
NAME varchar(100)
)
GO
INSERT test2(name) values('Fred')
INSERT test2(name) values('bert')
GO
DECLARE @name VARCHAR(100)
--SET @name='re'
SELECT * FROM test2
WHERE NAME LIKE CASE WHEN '%'+@Name+'%' IS NULL THEN NAME ELSE '%'+@Name+'%' END
如果我为@Name提供一个值,它只返回包含该值的名称,如果我将其保留,则返回所有名称?
答案 3 :(得分:0)
你真的想比较'%'+ @ Name +'%ESCAPE'\'为null吗?我想你想稍后放置escape关键字,如下所示:
CASE WHEN '%'+@Name+'%' IS NULL THEN NAME ELSE '%'+@Name+'%' ESCAPE '\' END