2014-09-22 47 views
1

我有一个看起来简单像这样的SQL Server存储过程:SQL服务器操作情况下,当我where子句

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参数是手机,我不希望u.PhoneNumber中的空值,并且当输入参数是电子邮件时,我不希望u.Email列中的值为空值。

解决此问题的最佳方法是什么?

回答

1

更改其中条件如下

where 
a.Active = 1 
and (
    (@Method = 'phone' and u.PhoneNumber is not null) 
    or 
    (@Method = 'email' and u.Email is not null) 
    ) 
+0

啊完美: ) 谢谢 – stibay 2014-09-22 08:47:19

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

它就像你的SELECT语句

where 
a.Active = 1 
and 
case 
    when @Method = 'phone' then u.PhoneNumber 
    when @Method = 'email' then u.Email 
end is not null