我有一个看起来简化的SQL Server存储过程:
begin
select
(
case
when @Method = 'phone' then u.PhoneNumber
when @Method = 'email' then u.Email
end
)
from
Table a
join
Users u on a.ID = u.Id
where
a.Active = 1
and
-- This part does not work
case
when @Method = 'phone' then u.PhoneNumber is not null
when @Method = 'email' then u.Email is not null
end
end
所以问题是我不想要空值,电话和电子邮件都可以为空。因此,如果@Method参数是phone,我不希望u.PhoneNumber
中的空值,当输入参数是电子邮件时,我不希望u.Email
列中包含空值。
解决这个问题的最佳方法是什么?
答案 0 :(得分:1)
您无需在可以使用的地方使用案例
where
a.Active = 1
and
-- This part now work
(
(@Method = 'phone' and u.PhoneNumber is not null) OR
(@Method = 'email' and u.Email is not null)
)
答案 1 :(得分:1)
更改您的位置条件如下
where
a.Active = 1
and (
(@Method = 'phone' and u.PhoneNumber is not null)
or
(@Method = 'email' and u.Email is not null)
)
答案 2 :(得分:1)
它就像你的选择陈述
where
a.Active = 1
and
case
when @Method = 'phone' then u.PhoneNumber
when @Method = 'email' then u.Email
end is not null