0

如果不为空,我想按@campId 过滤,如果为空,我想全部返回

这可以编译但不能按预期工作:

 declare @campId int
 select * 
 from cli 
 where 
    cu in (
        CASE @campId 
          when null then (select id from [dbo].[camp]) 
          else @campId 
        end) 
4

3 回答 3

1

如果 cu 从不为空

where cu = isnull(@campid, cu)
于 2012-10-23T10:36:53.193 回答
1

尝试这个:

select * 
from cli
where
   cu in (select  isnull(@campId, id) from [dbo].[camp])

这利用了这样一个事实,即从营地中选择将返回@campId,如果它不为空。

于 2012-10-23T10:37:19.747 回答
0

为什么不简单地使用IF语句?

DECLARE @campId AS INT

IF (@campId IS NULL) BEGIN
      SELECT [Column1], [Column2], ...
      FROM [dbo].[cli] AS C1
        INNER JOIN [dbo].[Camp] AS C2 ON C2.[Id] = C1.[Cu]  
END
ELSE BEGIN
      SELECT [Column1], [Column2], ...
      FROM [dbo].[cli] AS
      WHERE [Cu] = @camp    
END
于 2012-10-23T10:36:41.790 回答