T-SQL and the WHERE LIKE %Parameter% clause

后端 未结 3 1772
后悔当初
后悔当初 2020-11-30 06:28

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

相关标签:
3条回答
  • 2020-11-30 06:47

    you may try this one, used CONCAT

    WHERE LastName LIKE Concat('%',@LastName,'%')
    
    0 讨论(0)
  • 2020-11-30 06:52

    It should be:

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

    Instead of:

    ...
    WHERE LastName LIKE '%@LastName%'
    
    0 讨论(0)
  • 2020-11-30 07:00

    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 + '%'
    
    0 讨论(0)
提交回复
热议问题