代码之家  ›  专栏  ›  技术社区  ›  priyanka.sarkar

如何正确地为所提供的查询应用筛选器?

  •  1
  • priyanka.sarkar  · 技术社区  · 7 年前

    我下面有一张桌子

    declare @t table(bucket bigint null)
    
    insert into @t select 1 union all select 2 union all select -1 union all select 5
    

    现在让我写下下面的查询 (按Bucket 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
    

    declare @Bucket bigint = 2 –filter by 2
    select * from @t
    where 1=1
    AND (@Bucket is Null or @Bucket ='' or bucket=@Bucket)
    
    Result
    2
    

    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
    

    为什么bucket 0会出现这种行为?如何解决?

    2 回复  |  直到 7 年前
        1
  •  2
  •   D-Shih    7 年前

    你可以试着用 @Bucket bigint = NULL @Bucket 默认值。

    因为 NULL 意思是未知

    或者您可以设置一个不应该在 bucket 列不能是默认值。

    declare @Bucket bigint = NULL
    
    select * 
    from @t
    where (@Bucket is Null or bucket = @Bucket)
    

    注意

    但如果 @Bucket 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)
    
        2
  •  0
  •   Othman Dahbi-Skali    7 年前

    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)