James Wilson
James Wilson

Reputation: 5150

Having an issue with t-sql and case statement with and/where clause

SELECT 3 AS LoggedIn, 83 AS MessageID, Data AS DistID, 1 AS StatusID
    , 0 AS Important
    , CASE WHEN (dd.SponsorID = 3) THEN 0 ELSE d.ReceiveUplineMessages END AS Test
    , dd.SponsorID 
FROM msg_SplitVar(',', @MessageList) sv
INNER JOIN Distributor d 
    ON d.DistID = sv.Data
INNER JOIN DistributorDetail dd 
    ON dd.DistID = sv.Data
WHERE Data NOT IN (SELECT DistID FROM MessageBlockList WHERE BlockedID = 3)
    AND Test = 0

I have a field set in the distributor table ReceiveUplineMessages. This can be set to 0 or 1. If they set this to 0 I only want to send them a message if it is from their sponsor (logged in)

I have the case statement working, but I'm having trouble with the AND clause.

The splitVar function just takes a string based array '3,4,5,6,7' and splits the data out to individual rows for an insert statement.

Anyone know what I am doing wrong in the AND clause? I only want them to show up if ReceiveUplineMessages is a 0.

Upvotes: 1

Views: 209

Answers (1)

Taryn
Taryn

Reputation: 247830

try not using your Test alias in your WHERE clause:

SELECT 3 AS LoggedIn, 83 AS MessageID, Data AS DistID, 1 AS StatusID
    , 0 AS Important
    , CASE WHEN (dd.SponsorID = 3) THEN 0 ELSE d.ReceiveUplineMessages END AS Test
    , dd.SponsorID 
FROM msg_SplitVar(',', @MessageList) sv
INNER JOIN Distributor d 
    ON d.DistID = sv.Data
INNER JOIN DistributorDetail dd 
    ON dd.DistID = sv.Data
WHERE Data NOT IN (SELECT DistID FROM MessageBlockList WHERE BlockedID = 3)
    AND (CASE WHEN (dd.SponsorID = 3) THEN 0 ELSE d.ReceiveUplineMessages END) = 0

or wrap your statement in another SELECT to use your Test in the WHERE:

SELECT t.*    
FROM
(
    SELECT 3 AS LoggedIn, 83 AS MessageID, Data AS DistID, 1 AS StatusID
        , 0 AS Important
        , CASE WHEN (dd.SponsorID = 3) THEN 0 ELSE d.ReceiveUplineMessages END AS Test
        , dd.SponsorID 
    FROM msg_SplitVar(',', @MessageList) sv
    INNER JOIN Distributor d 
        ON d.DistID = sv.Data
    INNER JOIN DistributorDetail dd 
        ON dd.DistID = sv.Data
    WHERE Data NOT IN (SELECT DistID FROM MessageBlockList WHERE BlockedID = 3)
) t
WHERE t.Test = 0

Upvotes: 4

Related Questions