2015-05-14 76 views
3

我覺得必須有一個更有效的方法來做到這一點。我想允許呼叫者要麼把所有的書,或書籍中未隱藏(見下文)用WHERE子句重新設置簡單的SQL語句

if isnull(@ShowHiddenBooks, 0) = 1 
    begin 
     select 
      (long list of fields) 
     from 
      MyTable 
     where 
      MyField = @SomeField 
    end 
else 
    begin 
     select 
      (long list of fields) 
     from 
      MyTable 
     where 
      MyField = @SomeField and 
      IsHidden = 0  
    end 

有什麼想法?

謝謝!

回答

4
Select * 
from MyTable 
where MyField = @SomeField and 
(isHidden = 0 or @showHiddenBooks = 1) 
+0

這個失敗TI考慮到當@showHiddenBooks爲空。 – Steve

+0

@Steve,如果它爲空,它不會是1 – ps2goat

+0

@ ps2goat SQL的語義不同於C#,null = 1是真的 – Steve

2

這equivqlent到:

select (long list of fields) 
    from 
     MyTable 
    where 
     MyField = @SomeField and 
     (IsHidden = 0 or isnull(@ShowHiddenBooks, 0) = 1)