0

我正在尝试WHERE根据每个州或城市中存在的人数来更改条款。

如果一个州有超过 10 人,我希望WHERE是:

WHERE u.StateID = @StateID 

如果一个城市有超过 10 个人,我希望它是:

WHERE u.CityID = @CityID 

代替

WHERE u.StateID = @StateID

如果城市或州的人数不超过 10 人,我希望它是:

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
4

1 回答 1

2

您必须使用 AND/OR 运算符和嵌套条件而不是 CASE。

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

有些像这样。

更新

所以,这个例子真的不适合你。您需要更复杂的 where 子句。试试这个:

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

更新 2

这更好一点:

(@StateCount > 10 AND u.StateID = @StateID)
OR
(@StateCount <= 10 
    AND
    (
        (@CityCount > 10 AND CityID = @CityID)
        OR
        (@CityCount <= 10 AND CountryID = '1')
    )   
)
于 2012-04-13T08:37:20.260 回答