加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 07:45:39 所属栏目:MsSql教程 来源:网络整理
导读:这是我到目前为止在存储过程中使用两个声明的变量: 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_e
这是我到目前为止在存储过程中使用两个声明的变量:
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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读