现在本人有一个表里有一个字符串字段title,现在需要对该字段做模糊查询,而且like后面的条件希望通过@参数传入。不知道该怎么写?
如果是精确匹配可以写成下面的:
exec SP_executesql N'select * from table where title = @title', N'@title varchar(200)' ,N'testtitle'但是如果是模糊查询的话,好像不能写成:
exec SP_executesql N'select * from table where title like ''%@title%''', N'@title varchar(200)' ,N'testtitle'---注:我不希望用拼接sql语句的方式,即下面的方式 exec('select * from table where title like ''%'+@title+'%''')
的方式
如果是精确匹配可以写成下面的:
exec SP_executesql N'select * from table where title = @title', N'@title varchar(200)' ,N'testtitle'但是如果是模糊查询的话,好像不能写成:
exec SP_executesql N'select * from table where title like ''%@title%''', N'@title varchar(200)' ,N'testtitle'---注:我不希望用拼接sql语句的方式,即下面的方式 exec('select * from table where title like ''%'+@title+'%''')
的方式
go
exec SP_executesql N'select title_id from titles where title_id like @title', N'@title varchar(200)' ,N'BU%'--result
title_id
--------
BU1032
BU1111
BU2075
BU7832(4 row(s) affected)
非常感谢,这个问题困扰我2天了,终于解决了。