Using variable in SQL LIKE statement

前端 未结 9 1330
夕颜
夕颜 2020-12-05 08:52

I\'ve got a sproc (MSSQL 2k5) that will take a variable for a LIKE claus like so:

DECLARE @SearchLetter2 char(1)
SET @SearchLetter = \'t\'
SET @SearchLetter2         


        
9条回答
  •  一生所求
    2020-12-05 09:37

    We can write directly too...

    DECLARE @SearchLetter CHAR(1) 
    
    SET @SearchLetter = 'A' 
    
    SELECT * 
    FROM   CUSTOMERS 
    WHERE  CONTACTNAME LIKE @SearchLetter + '%' 
           AND REGION = 'WY' 
    

    or the following way as well if we have to append all the search characters then,

    DECLARE @SearchLetter CHAR(1) 
    
    SET @SearchLetter = 'A' + '%' 
    
    SELECT * 
    FROM   CUSTOMERS 
    WHERE  CONTACTNAME LIKE @SearchLetter 
           AND REGION = 'WY' 
    

    Both these will work

提交回复
热议问题