如何编写执行存储过程的触发器?

How to write a trigger that executes stored procedure?

我有一个计算人年龄的存储过程。这是:

ALTER PROCEDURE [dbo].[CalculateAge]
AS
    UPDATE Person
    SET Age = DATEDIFF(year, BirthDate,  GETDATE() ) 
    WHERE Age IS Null;

我想编写一个触发器,它会在添加新人时自动填充年龄列 是否可以编写一个触发器来执行上面编写的过程,或者在触发器中编写过程的逻辑更容易?

要在触发器内有效地使用过程,您需要传入一个参数,为此我们可以使用用户定义的 table。尽管根据问题,您的程序似乎只更新了所有行,因此不需要参数。

CREATE TRIGGER dbo.Person_Update ON dbo.Person AFTER UPDATE
AS
   EXEC dbo.CalculateAge 

此处最好的解决方案是不使用触发器,只需将计算列添加到 table

alter table MyTable add Age=Datediff(year, BirthDate,  Getdate())

这样查询 table.

时值总是正确的

有关计算列的完整详细信息,请参阅 documentation

编辑

要使用触发器实现如此简单的更新,在触发器中进行操作是有意义的

create trigger [dbo].[TriggerName] on dbo.TableName 
for insert 
as
if @@RowCount=0 return
set nocount on

update p set p.age=DateDiff(year, BirthDate, GetDate()) 
from inserted i
     join person p on p.Id = i.Id --<< Id is the primary key of the table