Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: Case with the statement "NOT IN"

I am trying to do a CASE statement in SQL Server (stored procedure) where I am supposed to check if whether or not it should get some results from another table.

I just made this up to illustrate the example (not working!)

SELECT
    *
FROM
    cards
WHERE
    CardID = @CardID
    AND
    CardID = 
        CASE WHEN @AlreadyOnDeck = 1 THEN
            IN (
                    SELECT CardID FROM OnDeckTable WHERE CardID = @CardID
            )
        CASE WHEN @AlreadyOnDeck = 0 THEN
            NOT IN (
                    SELECT CardID FROM OnDeckTable WHERE CardID = @CardID
            )
        END

I need to make the case IN / NOT IN depending on @AlreadyOnDeck variable

like image 868
janhartmann Avatar asked Aug 16 '26 02:08

janhartmann


2 Answers

Similar to Max's answer but uses CASE statements. (May produce a slightly better execution plan due to short circuiting of the outer CASE statement.)

SELECT
    *
FROM
    cards c
WHERE
    c.CardID = @CardID
    AND
    1 = (CASE WHEN @AlreadyOnDeck = 1 THEN 
                   (CASE WHEN EXISTS(select * OnDeckTable dt where dt.CardID = c.CardID) THEN 1 END)
              WHEN @AlreadyOnDeck = 0 THEN 
                   (CASE WHEN NOT EXISTS(select * from OnDeckTable dt where dt.CardID = c.CardID) THEN 1 END)       
        END)
like image 117
Moe Sisko Avatar answered Aug 19 '26 08:08

Moe Sisko


I think this will work, but haven't tested (no test data provided).

SELECT
    *
FROM
    cards
WHERE
    CardID = @CardID
    AND
    (
        exists (select 1 from OnDeckTable where CardId = @CardId and @AlreadyOnDeck = 1)
        or not exists (select 1 from OnDeckTable where CardId = @CardId and @AlreadyOnDeck = 0)
    )
like image 34
Derek Kromm Avatar answered Aug 19 '26 07:08

Derek Kromm



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!