我下面有一张桌子
declare @t table(bucket bigint null)
insert into @t select 1 union all select 2 union all select -1 union all select 5
现在让我编写以下查询(按存储桶0过滤-所有值都将出现)
declare @Bucket bigint = 0 –filter by 0
select * from @t
where 1=1
AND (@Bucket is Null or @Bucket ='' or bucket=@Bucket)
Result
1
2
-1
5
但是,如果我用2或其他任何值过滤Bucket,我将正确获得结果
declare @Bucket bigint = 2 –filter by 2
select * from @t
where 1=1
AND (@Bucket is Null or @Bucket ='' or bucket=@Bucket)
Result
2
如果我将其过滤为null或空白,则会得到正确的结果
declare @Bucket bigint = '' –filter by ''
select * from @t
where 1=1
AND (@Bucket is Null or @Bucket ='' or bucket=@Bucket)
Result
1
2
-1
5
为什么桶0会出现这种情况?以及如何解决?
答案 0 :(得分:2)
您可以尝试将@Bucket bigint = NULL
的默认值使用@Bucket
。
因为
NULL
意味着未知
或者您可以设置一个值,该值不应在bucket
列中为默认值。
declare @Bucket bigint = NULL
select *
from @t
where (@Bucket is Null or bucket = @Bucket)
注意
但是如果@Bucket bigint
为bigint,则不应为''
修改
CREATE TABLE T(
Bucket bigint
);
declare @Bucket bigint = 0
INSERT INTO T VALUES (1);
INSERT INTO T VALUES (2);
INSERT INTO T VALUES (-1);
INSERT INTO T VALUES (5);
INSERT INTO T VALUES (0);
select * from T
where (@Bucket is Null or (@Bucket ='' and @Bucket <> 0) or bucket=@Bucket)
答案 1 :(得分:0)
已修复
declare @t table(bucket bigint);
INSERT INTO @t VALUES (1);
INSERT INTO @t VALUES (2);
INSERT INTO @t VALUES (-1);
INSERT INTO @t VALUES (5);
INSERT INTO @t VALUES (0);
declare @Bucket bigint = 0 --filter by 0
select * from @t
where 1=1
AND (@Bucket is Null or cast(@Bucket as nvarchar) = '' or bucket=@Bucket)