Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable in SQL LIKE statement

Tags:

sql-server

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?

like image 271
Joel.Cogley Avatar asked Dec 23 '08 23:12

Joel.Cogley


People also ask

Can we use a variable in like in SQL?

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..." ). Show activity on this post. Show activity on this post.

How do you use variables in like statements?

Using the CONCAT() function, we can work with user variables in LIKE clause. The syntax is as follows. set @anyVariableName='anyValue'; select yourColumnName1,yourColumnName2,yourColumnName3,...

What does like %% mean in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

How do I assign a SQL query result to a variable?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.


2 Answers

If you are using a Stored Procedure:

ALTER PROCEDURE <Name> (     @PartialName VARCHAR(50) = NULL )  SELECT Name      FROM <table>     WHERE Name LIKE '%' + @PartialName + '%' 
like image 196
Andrew Brower Avatar answered Sep 22 '22 12:09

Andrew Brower


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.

like image 44
Eric Sabine Avatar answered Sep 21 '22 12:09

Eric Sabine