Search code examples
sql-server

Using variable in SQL LIKE statement


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 = @SearchLetter + '%'
SELECT *
    FROM BrandNames 
    WHERE [Name] LIKE @SearchLetter2 and IsVisible = 1 
    --WHERE [Name] LIKE 't%' and IsVisible = 1 
    ORDER BY [Name]

Unfortunately, the line currently running throws a syntax error, while the commented where clause runs just fine. Can anyone help me get the un-commented line working?


Solution

  • 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.