2014-09-22 73 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