T-SQL 和 WHERE LIKE %Parameter% 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14237755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
T-SQL and the WHERE LIKE %Parameter% clause
提问by dp3
I was trying to write a statement which uses the WHERE LIKE '%text%' clause, but I am not receiving results when I try to use a parameter for the text. For example, this works:
我试图编写一个使用 WHERE LIKE '%text%' 子句的语句,但是当我尝试为文本使用参数时没有收到结果。例如,这有效:
SELECT Employee WHERE LastName LIKE '%ning%'
This would return users Flenning, Manning, Ningle, etc. But this statement would not:
这将返回用户 Flenning、Manning、Ningle 等。但此语句不会:
DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%@LastName%'
No results found. Any suggestions? Thanks in advance.
未找到结果。有什么建议?提前致谢。
回答by Mahmoud Gamal
It should be:
它应该是:
...
WHERE LastName LIKE '%' + @LastName + '%';
Instead of:
代替:
...
WHERE LastName LIKE '%@LastName%'
回答by swe
The correct answer is, that, because the '%'
-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName
(be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'
正确答案是,因为'%'
-sign 是您搜索表达式的一部分,所以它应该是您的 VALUE 的一部分,所以无论您@LastName
在哪里设置(无论是来自编程语言还是来自 TSQL),您都应该将其设置为'%' + [userinput] + '%'
or, in your example:
或者,在您的示例中:
DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'
回答by Ramgy Borja
you may try this one, used CONCAT
你可以试试这个,用过CONCAT
WHERE LastName LIKE Concat('%',@LastName,'%')