简体   繁体   English

如何在存储过程中的t-sql动态语句中使用LIKE?

[英]How to use LIKE in a t-sql dynamic statement in a stored procedure?

I'm trying to use the LIKE keyword with the % wildcards wrapping the parameter, but I'm not sure how to get the % characters into the statement without breaking it. 我正在尝试使用包含参数的%通配符的LIKE关键字,但我不确定如何在不破坏它的情况下将%字符放入语句中。 Right now I have: 现在我有:

SET @SQLQuery = 'SELECT * FROM [tblApps] WHERE [firstName] LIKE %@search%'

I get a SqlException error in my .net app that says "Incorrect syntax near '@search' when I run it. The error goes away if I remove the % characters surrounding the @search parameter. 我的.net应用程序中出现SqlException错误,当我运行它时,“@ search”附近的语法不正确。如果删除@search参数周围的%字符,则错误消失。

The % characters have to be in the search string... %字符必须搜索字符串中...

SET @search = '%' + @search + '%'
SET @SQLQuery = 'SELECT * FROM [tblApps] WHERE [firstName] LIKE @search'

Note that the following would also work, but introduces potential for a SQL injection vulnerability... 请注意,以下内容也可以,但引入了SQL注入漏洞的可能性......

-- DON'T do this!
SET @SQLQuery = 'SELECT * FROM [tblApps] WHERE [firstName] LIKE ''%' + @search + '%'''
SET @SQLQuery = 'SELECT * from [tblApps] WHERE [firstName] LIKE ''%'' + @search + ''%'''
exec sp_executesql @query=@SQLQuery, @params=N'@search nvarchar(96)', @search=@search

The only difference from this version as compared to the others is that the dynamic execution of the sql is in fact parameterized which mitigates sql injection a bit. 与其他版本相比,与该版本的唯一区别在于,sql的动态执行实际上是参数化的,这有点减轻了sql注入。

SET @search = '%' + @search 
SET @SQLQuery = 'SELECT * FROM [tblApps] WHERE [firstName] LIKE ' + @search + '%'

This worked for me! 这对我有用!

SET @search = '''%' + @search + '%'''
SET @SQLQuery = 'SELECT * FROM [tblApps] WHERE [firstName] LIKE' + @search
EXEC sp_executesql @SQLQuery
declare @Cmd nvarchar(2000)
declare @eName varchar(10)
set @eName='a'
set @Cmd= 'select * from customer1 where name LIKE '''+'%' +@eName+ '%' + ''''
print @Cmd
EXECUTE sp_executesql @Cmd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM