Using variable in SQL LIKE statement

前端 未结 9 1325
夕颜
夕颜 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: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  WHERE variable1 like @variable
    

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

    提交回复
    热议问题