Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-factor simple SQL statement with WHERE clause

I feel there must be a more efficient way to do this. I want to allow the caller to either pull 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?

Thanks!

like image 713
Ricky Avatar asked Apr 15 '26 09:04

Ricky


2 Answers

Select *
from MyTable
where MyField = @SomeField and
(isHidden = 0 or @showHiddenBooks = 1)
like image 145
APH Avatar answered Apr 16 '26 23:04

APH


This is equivqlent to:

 select (long list of fields)
    from
        MyTable
    where
        MyField = @SomeField and
        (IsHidden = 0 or isnull(@ShowHiddenBooks, 0) = 1)
like image 43
Giorgi Nakeuri Avatar answered Apr 16 '26 23:04

Giorgi Nakeuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!