T-SQL 和 WHERE LIKE% Parameter% 子句

我尝试编写一个使用 WHERE LIKE’% text%’子句的语句,但是在尝试为文本使用参数时没有收到结果。例如,这种方法是有效的:

SELECT Employee WHERE LastName LIKE '%ning%'

这将返回用户 Flenning,Manning,Ningle 等,但这个声明不会:

DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%@LastName%'

没有发现任何结果。有什么建议吗? 提前谢谢。

169901 次浏览

It should be:

...
WHERE LastName LIKE '%' + @LastName + '%';

Instead of:

...
WHERE LastName LIKE '%@LastName%'

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] + '%'

or, in your example:

DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'

you may try this one, used CONCAT

WHERE LastName LIKE Concat('%',@LastName,'%')