带有 COALESCE 的 LIKE 运算符中的特殊字符不起作用

special character in LIKE Operator with COALESCE is not working

我有一篇文章 table 如下所示:

create table article(
  artID int,
  arttitle varchar(50)
  )

我在下面插入了4条记录:

insert into article values (1,'abcd');
insert into article values (2,'asfsdf asdf sdf ');
insert into article values (3,'asdfasdfa sd ');
insert into article values (4,'abcasdfsdd [Little]');

创建了一个测试存储过程:

create procedure test
@aID int = null,
@atit varchar(50) = null
as
select * from article where artID = COALESCE(@aID,artID) and 
arttitle like '%'+COALESCE(@atit,arttitle)+'%';

问题来了: 当我用 aid = 1 执行此 sp 时,它会产生该记录,并且对于 aid 2 和 3 也是如此。 但是当我用 aid = 4 执行时没有结果因为那些 square brackets [Little].

这里是存储过程执行脚本:

exec test @aID = 4;

请帮我实现这个。谢谢! 这是 sqlfiddle link

这是因为[]都是特殊字符,表示括号中的其中一个符号必须匹配。为了修复它 - 你可以逃避这些。

这是你可以做的:

DECLARE @article TABLE
(
    artID INT
    , arttitle VARCHAR(50)
);

INSERT INTO @article
VALUES (1, 'abcd')
    , (2, 'asfsdf asdf sdf ')
    , (3, 'asdfasdfa sd ')
    , (4, 'abcasdfsdd [Little]');

DECLARE @aID INT = 4
    , @atit VARCHAR(50) = NULL

SELECT *
FROM @article
WHERE artID = COALESCE(@aID, artID)
    AND arttitle LIKE '%' + COALESCE(@atit, REPLACE(REPLACE(arttitle, '[', '\['), ']', '\]')) + '%' ESCAPE '\';

我将 [ 替换为 \[,将 ] 替换为 \] 并转义了 \,以便将方括号视为随意字符。

如果您不想让 like 处理标题中的特殊字符,您可以只使用 charindex():

where @atit is null or charindex(@atit, artitle) > 0

如果要使用通配符,那么like是更好的选择。但这似乎不是你的本意。

实际上,即使使用 NULL,只需使用明确的 @atit is null or 即可解决您的问题。

create table article(
artID int,
arttitle varchar(50)
)

insert into article values (1,'abcd');
insert into article values (2,'asfsdf asdf sdf ');
insert into article values (3,'asdfasdfa sd ');
insert into article values (4,'abcasdfsdd [Little]');

create procedure test
declare
as
@aID int =4,
@atit varchar(50) = null

select * from article where artID = COALESCE(@aID,artID) and (@atit is null or charindex(@atit, arttitle) > 0)

如果您不想使用任何功能,您可以直接检查is null 检查下面 SQL。 select * from article where (@aID is null or artID = @aID) and (@atit is null or arttitle like '%'+ (@atit) +'%')