Re-run a simple SQL statement with a WHERE clause

I believe there must be a more efficient way for this. I want to allow the caller to either pull out ALL books or books that are not hidden (see below)

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

      

Any thoughts?

Thank!

+3


source to share


2 answers


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

      



+4


source


This is equivalent to:



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

      

+2


source







All Articles