在sp_executesql中使用LIKE [英] Using LIKE in sp_executesql
问题描述
SET @whereCond = @whereCond +'AND名称类似``%''+ @name +``%'''
SET @whereCond = @whereCond + ' AND name LIKE ''%'' + @name + ''%'''
这里有什么问题吗?生成where条件后,用sp_executesql
执行该条件,但没有得到任何结果.当我选择不带sp的相同东西时,就可以了.
Is there something wrong here? After I generate where condition, I execute it with sp_executesql
, but I did get anything. When I SELECT the same thing without sp, it's ok.
如何在sp_executesql中使用LIKE?你能举一些例子吗?
How to use LIKE in sp_executesql? Can you bring some examples, please?
谢谢.
更新
declare @name nvarchar(50)
set @name = 'a'
SELECT *
FROM Tbl_Persons WHERE 1 = 1 AND lastname LIKE '%a%'
exec sp_executesql
N'SELECT *
FROM Tbl_Persons WHERE 1 = 1 AND lastname LIKE ''%@name%''',
N'@name nvarchar(50)',
@name=@name
第一个查询返回值,第二个查询不返回任何值.
First query returns values, second one doesn't return anything.
有什么区别?
推荐答案
以下对我有用的
declare @name varchar(50)
set @name = 'WAITFOR'
exec sp_executesql
N'select * from sys.messages WHERE text LIKE ''%'' + @name + ''%''',
N'@name varchar(50)',
@name=@name
我认为问题必须出在其他地方.
I think the problem must lie elsewhere.
编辑:更新后,您需要使用
Following your update you need to use
exec sp_executesql
N'SET @name = ''%'' + @name + ''%'';
SELECT *
FROM Tbl_Persons WHERE 1 = 1 AND lastname LIKE @name',
N'@name nvarchar(50)',
@name=@name
按现状,您正在搜索包含实际子字符串@name
As it stands you are searching for text containing the actual substring @name
这篇关于在sp_executesql中使用LIKE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!