将字符串分解为where条件,
例如:“11 22 33 44 ” 生成 title like '%11%' and title like '%22%' and title like '%33%' and title like '%44%'
使用下面的函数:
SELECT [dbo].[f_split_where] ('11 22 33 44',' ','title')
DECLARE @str NVARCHAR(2000)
SET @str= 'SELECT TOP 11 * FROM table WHERE '+ [dbo].[f_split_where] ('为什么 中',' ','title')
EXEC sp_executesql @str
/*
分割字符串,用指定的分隔符,用指定的字段名称,生成并行条件
*/
ALTER function [dbo].[f_split_where](@c varchar(4000),@split varchar(2),@fieldstr VARCHAR(10))
returns varchar(2000)
as
begin
DECLARE @str VARCHAR(2000)='';
DECLARE @val VARCHAR(50)='';
SET @c=@c+@split;
while(charindex(@split,@c)<>0)
begin
SET @val=SUBSTRING(@c,1,charindex(@split,@c)-1);
IF @val=''
BEGIN
SET @c = stuff(@c,1,charindex(@split,@c),'');
CONTINUE;
END
SET @str+=@fieldstr +' like ''%'+@val+'%''';
SET @c = stuff(@c,1,charindex(@split,@c),'');
IF @c<>''
BEGIN
SET @str+=' and ';
END
end
return @str;
end
网友评论