Visual Studio SQL Server插入语句

时间:2016-11-17 18:54:30

标签: sql-server visual-studio

这是我的触发器。前两个UPDATE语句有效,但UPDATE学生不起作用。

 "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

2 个答案:

答案 0 :(得分: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触发器时,必须假设插入或删除了多个记录。 此外,您需要通过故意确保多个记录受初始插入或更新影响来测试触发器。创建触发器是不负责任的,假设一次只有一条记录插入,更新或删除。如果你不测试这样的行为,你将有一个触发器来创建数据完整性灾难,因为几乎所有的表最终都有多个记录插入/更新或删除。

答案 1 :(得分:0)

我认为你应该深入了解一下:

首先:您要从插入和事件表

中分配两次@EventID
SELECT @EventID=EventID from inserted
SELECT @EventID = EventID, @Points = Points from Event

第二:我想你会使用一些键读取事件表

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

然后,由于最后一句没有读过任何内容,@ Points可能没有价值。