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
The
char(4)variable will be padded out with three trailing spaces.These are significant in a
LIKEpattern and it will only match values ending in three spaces. Usevarchar(4)instead.