Transaction has ended in trigger. Batch has been aborted. Derived Attribute

前端 未结 1 454
清酒与你
清酒与你 2021-01-21 12:02

I have this trigger :

CREATE trigger [dbo].[DeriveTheAge] on [dbo].[Student]
after insert,update
as
begin
    declare @sid as int;
    declare @sdate as date;
          


        
1条回答
  •  清酒与你
    2021-01-21 12:26

    Why are you committing in the trigger? Why are you not handling multi-row inserts or updates? You can't just declare variables and assign them from inserted - what values do you think will get assigned when you update 2, or 15, or 6000 rows?

    CREATE TRIGGER [dbo].[DeriveTheAge] 
    ON [dbo].[Student]
    FOR INSERT, UPDATE
    AS
    BEGIN
        UPDATE s 
          SET Age = DATEDIFF(YEAR, [Date of Birth], CURRENT_TIMESTAMP)
          FROM dbo.Student AS s
          INNER JOIN inserted AS i
          ON s.[Student ID] = i.[Student ID]
          WHERE i.[Date of Birth] IS NOT NULL;
    END
    GO
    

    That all said, why on earth would you need a trigger to calculate someone's age? You can get this from the birth date right now at query time and know that it will be accurate, unlike this stale value you've stored in the table. Note that if their row is not updated for over a year, the age you've put in the table is out of date. When do you go back and update the Age for all rows in the table? Once a day? Anything less and your Age column is completely unreliable and pointless.

    Also, DATEDIFF(YEAR is not a reliable way to calculate age in the first place. All it does is count the number of year boundaries that have been crossed, it has no idea if the person's actual birthday is Jan 1 or Dec 31 or anywhere in between.

    Finally, I wouldn't print from the trigger. Who is going to consume that print statement when you're not debugging?

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