Using variable in SQL LIKE statement

前端 未结 9 1297
夕颜
夕颜 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:33

    As Andrew Brower says, but adding a trim

    ALTER PROCEDURE <Name>
    (
        @PartialName VARCHAR(50) = NULL
    )
    
    SELECT Name 
        FROM <table>
        WHERE Name LIKE '%' + LTRIM(RTRIM(@PartialName)) + '%'
    
    0 讨论(0)
  • 2020-12-05 09:34

    DECLARE @SearchLetter2 char(1)

    Set this to a longer char.

    0 讨论(0)
  • 2020-12-05 09:35

    It may be as simple as LIKE '%%[%3]%%' being [%3] the input variable.

    This works for me with SAP B1 9.1

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-05 09:39

    I had also problem using local variables in LIKE.
    Important is to know: how long is variable.
    Below, ORDER_NO is 50 characters long, so You can not use: LIKE @ORDER_NO, because in the end will be spaces.
    You need to trim right side of the variable first.
    Like this:

    DECLARE @ORDER_NO char(50)
    SELECT @ORDER_NO = 'OR/201910/0012%'
    
    SELECT * FROM orders WHERE ord_no LIKE RTRIM(@ORDER_NO)
    
    0 讨论(0)
  • 2020-12-05 09:43

    This works for me on the Northwind sample DB, note that SearchLetter has 2 characters to it and SearchLetter also has to be declared for this to run:

    declare @SearchLetter2 char(2)
    declare @SearchLetter char(1)
    Set @SearchLetter = 'A'
    Set @SearchLetter2 = @SearchLetter+'%'
    select * from Customers where ContactName like @SearchLetter2 and Region='WY'
    
    0 讨论(0)
提交回复
热议问题