声明的变量与硬编码字符串的行为不同

Joe*_*Joe 5 sql sql-server variables

我试图将一个like参数设置为一个变量,并允许该变量接受通配符(mssql 2005).如果我使用我的参数设置为'%'它只返回一个部分子集但如果我硬编码查询使用'%'它返回完整集.为什么变量的行为与字符串不同?

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

VS

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

完整场景是基于标志进行切换,但在上面的代码下可以重现

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;
Run Code Online (Sandbox Code Playgroud)

谢谢

Mar*_*ith 9

char(4)变量有三个尾随空格进行填充.

这些LIKE模式中重要,它只匹配以三个空格结尾的值.请varchar(4)改用.