2015-06-08 13 views
6

Mam tabelę zdarzeń, która ma pole autor i pole prezentera. Osoba z mojej tabeli osób może być zarówno autorem, jak i prezenterką tego samego wydarzenia lub może być zarówno prezenterem, jak i autorem. Muszę zastosować filtry do zestawu wyników na podstawie ich identyfikatora osoby i wybranego typu lub filtru. Dostępne filtry to:SQL Select Statement Where

Wszystkie: Zwraca wszystkie rekordy, w których są autorami lub prezenterami.

AllPresenter: wszystkie rekordy jako prezenter.

AllAuthor: wszystkie rekordy jako autor.

PresenterOnly: tylko rekordy jako prezenter, a nie autor.

AuthorOnly: tylko rekordy jako autor, a nie prezenter.

PresenterAndAuthorOnly: wszystkie rekordy, w których są prezenterem i autorem.

Obecnie przechowuję proc, który używa zewnętrznych ifs jak ten poniżej i próbowałem znaleźć sposób na połączenie wszystkich podobnych stwierdzeń w jedno. Nie miałem szczęścia znaleźć lepszego rozwiązania i zastanawiam się, czy brakuje mi techniki.

If (@filter = 'PandAOnly' or @filter = 'AllP' or @filter = 'AllA') 
begin 
    Select * from Event 
    Where 
     PresenterId = Case @personId is null then PresenterId else @personId end 
     and 
     AuthorId = Case @personId is null then AuthorId else @personId end 
end 
else if (@filter = 'All') 
begin 
    Select * from Event 
    Where 
     PresenterId = @personId 
     Or 
     AuthorId = @personId 
end 
else if (@fitler = 'POnly') 
begin 
    Select * from Event 
    Where 
     PresenterId = @personId 
     and 
     AuthorId <> @personId 
end 
else 
begin 
    Select * from Event 
    Where 
     AuthorId = @personId 
     and 
     PresenterId <> @personId 
end 

Odpowiedz

5
Select * from Event 
Where 
    (
     ((@personId is null) OR (PresenterId [email protected])) 
     and 
     ((@personId is null) OR (AuthorId = @personId)) 
     AND 
     (@filter = 'PandAOnly' or @filter = 'AllP' or @filter = 'AllA') 
    ) 
OR 
    (
     (PresenterId = @personId 
     Or 
     AuthorId = @personId) 
    AND (@filter = 'All') 
) 
OR 
    (
     PresenterId = @personId 
     and 
     AuthorId <> @personId 
     and 
     @fitler = 'POnly' 
) 
OR 
(
     AuthorId = @personId 
     and 
     PresenterId <> @personId 
     and 
     @fitler = 'AOnly' 
) 

UWAGA

Wolałbym trzymać się procedury przechowywanej, plan wykonania dla powyższego zapytania będzie straszny :)