2011-03-04 73 views
6

這裏是我迄今爲止使用兩種宣佈在存儲過程中的變量:SQL Server存儲過程添加兩個聲明的值總

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一起獲得總點?我可以使用「+」添加它們並將其分配給第三個聲明變量還是隻有一個總體聲明?

感謝,

詹姆斯

+0

這方面的一個更合適的標題會一直這樣做「兩聲明的變量「而不是價值。感謝所有反應如此迅速的人。 – James 2011-03-05 04:09:56

回答

11

如果您不需要兩個組件變量了,你可以(重新)使用的變量之一:

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

不過要小心加時SUM()'s,因爲它們可以是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) 
+0

謝謝。要知道,也可以使用另一個變量(@TotalPoints)並將前兩個變量加在一起? – James 2011-03-04 04:32:13

+0

@詹姆斯這是可能的,因爲@理查德已經在他的一個例子中顯示(@TotalPoints)。 – 2011-03-04 04:38:19

+0

回覆的人都回答了我的問題,但包括處理空值的信息非常有幫助。我將不得不處理這個問題,因爲參加者可能有回答問題的觀點,但不包括參加活動(反之亦然)。 – James 2011-03-05 04:06:04

1

如果您需要@QuestionPoints和@EventPoints保留其當前值,那麼,你需要一個第三個變量:

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

如果您不需要它們來保留其相同的值,那麼您可以覆蓋其中的一個:

SET @QuestionPoints = @QuestionPoints + @EventPoints

或者,在最新版本的SQL:

SET @QuestionPoints += @EventPoints

0

你可以在一個單獨的語句

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 
       )