我有以下代码
IF EXISTS(SELECT @FunderID
FROM dbo.FunderCharityTbl
WHERE @ContributionAmount > ( ( sum(TotalContributions) / 100 ) *10 ))
BEGIN
RAISERROR ('Sorry contribution is refused limit is breached', 16,1)
RETRUN 99
END
我收到以下错误
Msg 147,Level 15,State 1,Procedure InsertContribution,Line 33
聚合可能不会出现在WHERE子句中,除非它在a中 包含在HAVING子句或选择列表中的子查询以及列 被聚合是一个外部参考。
我要做的是检查@contributionAmount
(输入的金额)是否大于输入的funderID
的所有先前捐款的10%以及是否发送了错误消息
我对SQL比较陌生,我想知道为什么你不能按照我编写它的方式编写If Exists
语句,我需要做些什么来修复这个错误并让我的程序执行和我想要的一样。
答案 0 :(得分:1)
您必须使用GROUP BY
和HAVING
之类的内容:
IF EXISTS(
SELECT @FunderID
FROM dbo.FunderCharityTbl
GROUP BY @FunderID
HAVING @ContributionAmount > ((sum(TotalContributions)/100)*10)
)
答案 1 :(得分:1)
您不能在WHERE
子句中使用聚合函数,但可以在HAVING
子句中使用它
IF EXISTS( SELECT 1 --@FunderID
FROM dbo.FunderCharityTbl
HAVING @ContributionAmount > ((sum(TotalContributions)/100)*10)
)
答案 2 :(得分:1)
我认为该消息非常明确:您不能在where
子句中使用聚合函数。适当的条款是having
。
您的查询意图尚不清楚。为什么要返回变量值?事实上,使用EXISTS
,您可以返回任何内容。我更喜欢SELECT 1
。
我猜您正在尝试确定@FunderID
是否超过了某个级别的贡献。您可以这样做:
IF ( (SELECT (sum(TotalContributions)/100)*10
FROM dbo.FunderCharityTbl
WHERE FunderId = @FunderId
) > @ContributionAmount
)
BEGIN
. . .
END;
注意:我还建议您在使用BEGIN
时使用END
/ IF
块。
另一种解释是,您要确定任何资助者捐赠的金额是否超过指定金额:
IF (EXISTS (SELECT (sum(TotalContributions)/100)*10
FROM dbo.FunderCharityTbl
GROUP BY FunderId
HAVING sum(TotalContributions)/100)*10 > @ContributionAmount
)
)
BEGIN
. . .
END;