SQL Server Stored Procedure Adds Two Declared Values ​​for Total

Here is what I have used so far with two declared variables in a stored procedure:

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) 

How can I add @QuestionPoints and @EventPoints together to get total points? Can I just add them with a β€œ+” and assign them to the third declared variable or have one common statement?

Thanks,

James

+6
sql sql-server-2008 stored-procedures sum
source share
3 answers

If you no longer need two component variables, you can (re) use one of the variables:

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

Be careful when adding SUM() 's, because they can be NULL. 20 + null => null . Use ISNULL if necessary, e.g.

 SET @QuestionPoints = isnull(@QuestionPoints, 0) + isnull(@EventPoints, 0) 

If you still need them, you can declare a third.

 DECLARE @TotalPoints float --- or numeric or whatever the type should be SET @TotalPoints = @QuestionPoints + @EventPoints 

You can even skip individual variables

 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) 
+11
source share

If you need @QuestionPoints and @EventPoints to keep their current values, then yes, you need a third variable:

 DECLARE @totalPoints INT SET @totalPoints = @QuestionPoints + @EventPoints 

If you do not need them to keep the same value, you can simply overwrite one of them:

SET @QuestionPoints = @QuestionPoints + @EventPoints

Or, in recent versions of SQL:

SET @QuestionPoints += @EventPoints

+1
source share

You can do it in one expression

 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 ) 
0
source share

All Articles