SQL Server存储过程为total添加两个声明的值

这是我到目前为止在存储过程中使用两个声明的变量:
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)
    
如果你需要@QuestionPoints和@EventPoints来保留它们的当前值,那么是的,你需要第三个变量:
DECLARE @totalPoints INT
SET @totalPoints = @QuestionPoints + @EventPoints
如果您不需要它们保留相同的值,那么您可以覆盖其中一个:
SET @QuestionPoints = @QuestionPoints + @EventPoints
或者,在最新版本的SQL中:
SET @QuestionPoints += @EventPoints
    
你可以在一个声明中做到这一点
Set @Total =    (
                Select Sum( Z.points )
                From    (
                        Select points
                        From tb_responses
                        Where userid = @UserId
                            And Id = @Id
                        Union All
                        Select E.points
                        From dbo.tb_attendance As A
                            Join dbo.tb_events As E
                                On E.dbid = A.eventid
                        Where A.userid = @UserId
                            And A.didattend = 'Y'
                            And E.Id = @ID
                        ) As Z
                )
    

要回复问题请先登录注册