SQL CASE WHEN 参数不为空

SQL CASE WHEN Parameter is not empty

我有以下 table:

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

然后我有一个 parameter 叫做 @groupid
如果参数是A,那么结果一定是select的所有记录。但是如果参数不是 A 那么结果应该只查看 selected 参数。

例如,如果 parameterB 那么结果应该是:

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

例如,如果 parameterA 那么结果应该是:

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

有什么想法吗?
谢谢。

这非常违反直觉,我强烈建议不要这样做。不过,您可以使用类似的东西:

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

这似乎是你想要的逻辑:

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

如果输入为'A',则所有记录都匹配,否则输入只有returns条groupid值匹配的记录。

这是我的模型 table,只需将 @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;