SQL CASE WHEN参数不为空

时间:2018-10-11 08:15:24

标签: sql tsql sql-server-2014

我有下表:

-------------------------------------
groupid      value                   
-------------------------------------
A            10
A            15
B            20
C            50

然后我有一个parameter,叫做@groupid
如果参数为A,则结果必须选择所有记录。但是,如果参数不是A,则结果应仅查看所选参数。

例如,如果parameterB,则结果应为:

-------------------------------------
groupid      value                   
-------------------------------------
B            20

例如,如果parameterA,则结果应为:

-------------------------------------
groupid      value                   
-------------------------------------
A            10
A            15
B            20
C            50

有什么主意吗?
谢谢。

3 个答案:

答案 0 :(得分:2)

这是我对模型表的看法,只需将@groupid更改为任何参数'A', 'B' or 'C'

declare @table table (groupId varchar(20), value int)
insert into @table
select 'A',            10 union all
select 'A',            15 union all
select 'B',            20 union all
select 'C',            50

declare @groupid varchar(2)='B'



    SELECT *
    FROM @table
    WHERE  
        'A'= @groupid 
        OR 
        groupid = @groupid;

答案 1 :(得分:1)

这似乎是您想要的逻辑:

SELECT *
FROM yourTable
WHERE @groupid = 'A' OR groupid = @groupid;

如果输入为'A',则所有记录都匹配,否则输入仅返回其groupid值匹配的记录。

答案 2 :(得分:0)

这是非常违反直觉的,我强烈建议不要这样做。不过,您可以使用类似以下内容的

select groupid,value
from   tablename
where  @groupid = 'A'
    OR (@groupid <> 'A' AND @groupid = groupid)

一种不太混乱的方法是:

select groupid,value
from   tablename
where  @groupid IS NULL
    OR @groupid = groupid