user1007103
user1007103

Reputation: 425

Using a CASE statement in a SQL Server WHERE clause

I'm trying to change the WHERE clause depending how many persons that exist in each State or City.

If there are more then 10 people in a state I want the WHERE to be:

WHERE u.StateID = @StateID 

If there are more then 10 people in a city I want it to be:

WHERE u.CityID = @CityID 

instead of

WHERE u.StateID = @StateID

If there aren't more then 10 people in either city or state I want it to be:

WHERE u.CountryID = '1'



ALTER PROCEDURE GetHighscore
(@UserID int)
AS
BEGIN
Declare @StateCount int
Declare @CityCount int
Declare @StateID int
Declare @CityID int

SELECT @StateID=StateID FROM tblUser WHERE UserID = @UserID

SELECT @CityID=CityID FROM tblUser WHERE UserID = @UserID

SELECT  @StateCount=COUNT(DISTINCT tblUserTrix.UserID)
FROM            tblUserTrix INNER JOIN
                         tblUser ON tblUserTrix.UserID = tblUser.UserID
WHERE        (tblUser.StateID = @StateID)

SELECT @CityCount=COUNT(DISTINCT tblUserTrix.UserID)
FROM            tblUserTrix INNER JOIN
                         tblUser ON tblUserTrix.UserID = tblUser.UserID
WHERE        (tblUser.CityID = @CityID)


SELECT TOP 10        ut.UserID, SUM(t.Hardness) AS TotalTrixPoints, u.FirstName, u.LastName, u.StateID, u.CityID, tblSweCitys.CityName
FROM            tblUserTrix AS ut INNER JOIN
                         tblUser AS u ON ut.UserID = u.UserID INNER JOIN
                         tblState ON u.StateID = tblState.StateID INNER JOIN
                         tblCitys ON u.CityID = tblCitys.CityID LEFT OUTER JOIN
                         tblTrix AS t ON ut.TrixID = t.TrixID

WHERE CASE 
WHEN @StateCount > 10 
THEN u.StateID = @StateID

WHEN @CityCount > 10 
THEN u.CityID = @CityID
ELSE u.CountryID = '1'
        END = ?

GROUP BY ut.UserID, u.FirstName, u.LastName, u.CityID, u.StateID, tblCitys.CityName
ORDER BY TotalTrixPoints DESC   

END

Upvotes: 0

Views: 789

Answers (1)

Alexander Burov
Alexander Burov

Reputation: 1322

You must use AND / OR operators and nested conditions instead of CASE.

(@StateCount > 10 AND u.StateID = @StateID) OR (@CityCount > 10 AND CityID = @CityID) OR (CountryID = '1')

Some like this.

UPDADE:

So, really this example wasn't work properly for you. You need more complex where clause. Try this:

(@StateCount > 10 AND u.StateID = @StateID)
OR
(@CityCount > 10 AND @StateCount <= 10 AND CityID = @CityID)
OR
(@StateCount <= 10 AND @CityCount <= 10 AND CountryID = '1')

UPDATE 2

And this a little better:

(@StateCount > 10 AND u.StateID = @StateID)
OR
(@StateCount <= 10 
    AND
    (
        (@CityCount > 10 AND CityID = @CityID)
        OR
        (@CityCount <= 10 AND CountryID = '1')
    )   
)

Upvotes: 2

Related Questions