Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declared variable behaving differently to hard coded string

I am trying to set a like parameter into a variable and allow that variable to accept wild cards (mssql 2005). If I use my parameter set to '%' it only returns a partial subset but if I hard code the query to use '%' it returns the full set. Why might the variable behave differently to the string?

DECLARE @wareno char(4); 
SET @wareno = '%';
select @wareno as a, * from waredesc where wareno like @wareno;

vs

DECLARE @wareno char(4); 
SET @wareno = '%';
select @wareno as a, * from waredesc where wareno like '%';

The full scenario is switching based on a flag but is reproducible under the code above

DECLARE @wareno char(4); 
DECLARE @delprods bit;

/**
SET THESE PARAMETERS
**/
SET @wareno = '1'; 
SET @delprods = 'true'; /** if true all the warehouses should also be emptied for safety - products are held at a company level!**/

IF @delprods = 1
BEGIN
    SET @wareno = '%';
END
select @wareno as a, * from waredesc where wareno like @wareno;

Thanks

like image 812
Joe Avatar asked Nov 05 '12 13:11

Joe


1 Answers

The char(4) variable will be padded out with three trailing spaces.

These are significant in a LIKE pattern and it will only match values ending in three spaces. Use varchar(4) instead.

like image 187
Martin Smith Avatar answered Sep 30 '22 15:09

Martin Smith