gpt4 book ai didi

sql - SQL Server存储过程为总数添加两个声明的值

转载 作者:行者123 更新时间:2023-12-04 13:34:52 24 4
gpt4 key购买 nike

到目前为止,这是我在存储过程中使用两个声明的变量的结果:

SET @QuestionPoints = (SELECT SUM(points) 
FROM tb_responses
WHERE userid = @UserId
AND id = @ID)
SET @EventPoints =(SELECT SUM(dbo.tb_events.points)
FROM dbo.tb_attendance
INNER JOIN dbo.tb_events
ON dbo.tb_attendance.eventid = dbo.tb_events.dbid
WHERE dbo.tb_attendance.userid = @UserID
AND dbo.tb_attendance.didattend = 'Y'
AND dbo.tb_events.id = @ID)

如何将@QuestionPoints和@EventPoints加在一起以得到总积分?我可以仅使用“+”将它们添加并分配给第三个声明的变量,还是可以有一个整体语句?

谢谢,

詹姆士

最佳答案

如果您不再需要两个组成变量,则可以(重新)使用其中一个变量:

SET @QuestionPoints = ...
SET @EventPoints = ...
SET @QuestionPoints = @QuestionPoints + @EventPoints

不过,在添加 SUM()时要小心,因为它们可以为NULL。 20 + null => null。如有必要,请使用ISNULL,例如
SET @QuestionPoints = isnull(@QuestionPoints, 0) + isnull(@EventPoints, 0)

如果仍然需要它们,则可以声明第三个。
DECLARE @TotalPoints float  --- or numeric or whatever the type should be
SET @TotalPoints = @QuestionPoints + @EventPoints

您甚至可以跳过各个变量
SET @QuestionPoints = (SELECT SUM(POINTS) FROM tb_Responses WHERE UserID = @UserId AND ID = @ID)
+
(SELECT SUM(dbo.tb_Events.Points) FROM dbo.tb_Attendance INNER JOIN dbo.tb_Events ON dbo.tb_Attendance.EventID = dbo.tb_Events.dbID WHERE dbo.tb_Attendance.UserID = @UserID AND dbo.tb_Attendance.DidAttend = 'Y' AND dbo.tb_Events.ID = @ID)

关于sql - SQL Server存储过程为总数添加两个声明的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5189643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com