2016-11-17 112 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