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

Jam*_*mes 6 sql stored-procedures sum sql-server-2008

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

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) 
Run Code Online (Sandbox Code Playgroud)

如何将@QuestionPoints和@EventPoints一起添加以获得总积分?我可以使用"+"添加它们并分配给第三个声明的变量或者有一个整体声明吗?

谢谢,

詹姆士

Ric*_*iwi 11

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

SET @QuestionPoints = ...
SET @EventPoints = ...
SET @QuestionPoints = @QuestionPoints + @EventPoints 
Run Code Online (Sandbox Code Playgroud)

添加SUM()' 时要小心,因为它们可以为NULL. 20 + null => null.必要时使用ISNULL,例如

SET @QuestionPoints = isnull(@QuestionPoints, 0) + isnull(@EventPoints, 0)
Run Code Online (Sandbox Code Playgroud)

如果你仍然需要它们,那么你可以宣布第三个.

DECLARE @TotalPoints float  --- or numeric or whatever the type should be
SET @TotalPoints = @QuestionPoints + @EventPoints 
Run Code Online (Sandbox Code Playgroud)

你甚至可以跳过各个变量

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)
Run Code Online (Sandbox Code Playgroud)