微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 =>空值.必要时使用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)

原文地址:https://www.jb51.cc/mssql/76486.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐