如果不为空,我想按@campId 过滤,如果为空,我想全部返回
这可以编译但不能按预期工作:
declare @campId int
select *
from cli
where
cu in (
CASE @campId
when null then (select id from [dbo].[camp])
else @campId
end)
如果不为空,我想按@campId 过滤,如果为空,我想全部返回
这可以编译但不能按预期工作:
declare @campId int
select *
from cli
where
cu in (
CASE @campId
when null then (select id from [dbo].[camp])
else @campId
end)
如果 cu 从不为空
where cu = isnull(@campid, cu)
尝试这个:
select *
from cli
where
cu in (select isnull(@campId, id) from [dbo].[camp])
这利用了这样一个事实,即从营地中选择将返回@campId,如果它不为空。
为什么不简单地使用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