2016-11-17 116 views
0

這是我的觸發器。前兩個UPDATE語句有效,但UPDATE Student不起作用。Visual Studio SQL Server插入語句

"UPDATE Student SET PointsAccumulated = PointsAccumulated + @Points 
      Where @StudentID = StudentID" 


CREATE TRIGGER [Trigger] 
ON [dbo].[Attendance] 
After insert 
AS 
BEGIN 
    DECLARE @EventID int 
    Declare @StudentID nchar 
    DECLARE @Points int 

    SELECT @EventID=EventID from inserted 
    SELECT @EventID = EventID, @Points = Points from Event 
    SELECT @StudentID = StudentID from inserted 

    Update Event SET Attendance = Attendance + 1 
     WHERE @EventID = EventID 

    UPDATE Attendance SET Points = @Points 
     Where @EventID = EventID 

    UPDATE Student SET PointsAccumulated = PointsAccumulated + @Points 
     Where @StudentID = StudentID 

是爲我工作從HLGEM解決方案:

Update E 
    SET Attendance = Attendance + 1 
    FROM Event E 
    JOIN Inserted I ON i.eventid = e.eventid 


    UPDATE A 
    SET Points = e.points 
    FROM Attendance a 
    JOIN Event E ON a.EventID = e.EventID 
    JOIN Inserted I ON i.EventID = e.EventID 


    UPDATE S 
    SET PointsAccumulated = PointsAccumulated + e.points 
    FROM Student S 
    JOIN Inserted I ON i.studentID = s.studentID 
    JOIN Event E ON i.eventid = e.eventid 

經驗教訓: 在SQL Server中,這是從來沒有適合使用的變量(比表變量等)搶什麼在表中改變了一個觸發器,因爲他們沒有在其他一些數據庫 --HLGEM

+0

它是否產生任何錯誤或只是不更新​​?你能確保Where @StudentID = StudentID返回結果。 –

+0

沒有錯誤 – wes

+2

您正在設置來自Event表的Points變量,並且沒有where條件。我的心理猜測是,積分不包含你認爲它包含的內容。如果沒有where子句,它將被設置爲表中其中一條記錄的值......哪一個......誰知道! – Jeremy

回答

1

這不是測試,但我認爲這是你需要的東西:

CREATE TRIGGER [Trigger] 
ON [dbo].[Attendance] 
After insert 
AS 
BEGIN 



    Update E 
    SET Attendance = Attendance + 1 
    FROM Event E 
    JOIN Inserted I ON i.eventid = e.eventid 


    UPDATE A 
    SET Points = e.points 
    FROM Attendance a 
    JOIN Event E ON a.eventid = e.eventid 
    JOIN Inserted I ON i.eventid = e.eventid 


    UPDATE S 
    SET PointsAccumulated = PointsAccumulated + e.points 
    FROM Students s 
    JOIN Inserted I ON i.StudentID = e.StudentID 
    JOIN Event E ON i.eventid = e.eventid 

注意這修復不正確的前兩個的更新。在編寫SQL Server觸發器時,您必須假定在插入或刪除中會有多條記錄。 此外,您需要通過故意確保多個記錄受到初始插入或更新的影響來測試觸發器。假設一次只有一個記錄被插入,更新或刪除,創建觸發器是不負責任的。如果你不這樣做,你將會有一個觸發器產生數據完整性災難,因爲幾乎所有的表最終都會有多個記錄插入/更新或刪除。

0

我想你應該深吸樣子觸發器工作一行接一行:

第一:你分配兩次@EventID,從插入和事件表

SELECT @EventID=EventID from inserted 
SELECT @EventID = EventID, @Points = Points from Event 

二:我想你會使用一些關鍵的閱讀事件表

SELECT @Points = Points from Event "WHERE EventID = @EventID" 

然後,@Points也許沒有價值,因爲這最後一句話沒有讀過任何東西。

+0

雖然你的意見對某些錯誤是正確的,但是你還沒有修復假設插入只有一條記錄的最糟糕的錯誤。在SQL Server中,使用變量(表變量除外)來獲取觸發器中表中更改的內容是不合適的,因爲它們不像某些其他數據庫中的觸發器一樣工作成行... – HLGEM

+0

嗨! @HLGEM,謝謝,我知道,但正試圖解決這個問題。我有一個很多觸發器的舊數據庫,我可以向你保證這是一個非常頭痛的問題。我個人更喜歡處理存儲過程,甚至比在代碼中使用業務層更好。 – McNets

+0

我個人更喜歡觸發器,因爲應用程序代碼之外的數據庫有很多動作。 – HLGEM