Trigger that updates just the inserted row

前端 未结 2 1795
醉话见心
醉话见心 2020-12-30 03:54

I\'m trying to create a simple trigger using TSQL (or SQL Server 2008). The problem is: my current trigger is updating the entire table. This was fine for a while, but now t

相关标签:
2条回答
  • 2020-12-30 04:01

    If it is necessary to use a trigger here at all I would use an INSTEAD OF trigger to adjust the values pre-insert and avoid the need to JOIN back onto the base table and Update them afterwards.

    CREATE TRIGGER trig_MyPplUpdate
    ON [Persons]
    INSTEAD OF INSERT
    AS
      BEGIN
          INSERT INTO Persons
          SELECT foo,
                 bar,
                 CASE
                   WHEN Len(MyFile) >= 60 THEN MyFile
                 END
          FROM   Inserted
      END  
    
    0 讨论(0)
  • 2020-12-30 04:01

    You need to join the Inserted pseudo table in your UPDATE statement. Always be aware that SQL Server fires the trigger once per statement and that statement can very well modify/insert multiple rows at once - so your Inserted table quite likely will contain more than one row - just need to keep that in mind when you write your trigger.

    Try something like this:

    CREATE TRIGGER trig_MyPplUpdate
    ON [Persons]
    FOR INSERT
    AS
        UPDATE dbo.Persons
        SET MyFile = NULL
        WHERE Len(MyFile) < 60
        AND PersonID IN (SELECT DISTINCT PersonID FROM Inserted)
    

    or use whatever unique column (your primary key) you have to get exactly those rows that have been inserted.

    0 讨论(0)
提交回复
热议问题