Using variable in SQL LIKE statement

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

    If you are using a Stored Procedure:

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

    But in my opinion one important thing.

    The "char(number)" it's lenght of variable.

    If we've got table with "Names" like for example [Test1..Test200] and we declare char(5) in SELECT like:

    DECLARE @variable char(5)
    SET @variable = 'Test1%'
    SELECT * FROM table WHERE Name like @variable
    

    the result will be only - "Test1"! (char(5) - 5 chars in lenght; Test11 is 6 )

    The rest of potential interested data like [Test11..Test200] will not be returned in the result.

    It's ok if we want to limit the SELECT by this way. But if it's not intentional way of doing it could return incorrect results from planned ( Like "all Names begining with Test1..." ).

    In my opinion if we don't know the precise lenght of a SELECTed value, a better solution could be something like this one:

    DECLARE @variable varchar(max)
    SET @variable = 'Test1%'
    SELECT * FROM <table> WHERE variable1 like @variable
    

    This returns (Test1 but also Test11..Test19 and Test100..Test199).

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

    Joel is it that @SearchLetter hasn't been declared yet? Also the length of @SearchLetter2 isn't long enough for 't%'. Try a varchar of a longer length.

    0 讨论(0)
提交回复
热议问题