创建触发器以存储审计跟踪

Creating a trigger to store an audit trail

我必须在 Claims table 上创建一个触发器,只要将新记录插入 Claims table 就会触发该触发器。此触发器应存储客户名称和该客户的总计 amount_of_claim

Claim_audits(审核table)已经创建。

架构:

Claims

id int(11)
status_id int(11)
customer_policy_id int(11)
date_of_claim date
amount_of_claim float

> one or many to one(and only one) towards Customer_policy

Customer_policy

id int(11)
policy_start_date date
policy_renewal_date date
policy_id int(11)
customer_id int(11)
agent_id(11)

> one or many to one (and only one) towards Customer

Customer

id int(11)
first_name varchar(30)
last_name varchar(30)
email varchar(30)
address_id int(11)

输出应如下所示:

customer_name   amount_of_claim
abhinav         195000

这是我试过的:

CREATE TRIGGER claim_audits on claims 
for insert
as
    declare @custname varchar(25);
    declare @amount varchar(25);
    declare @action varchar(25);
    
    select @custname = first_name from customer c
    join inserted i on i.id=c.id;
    select @amount = i.amount_of_claim from inserted i;
    select @action = 'Updated customer claimed amount';
    
    insert into claim_audits values(@custname , @amount , @action);
    select * from claim_audits; 
go

Inserted 伪table 可以有 0-N 行,你需要处理它。与任何 SQL 相关的事物一样,您应该使用基于集合的方法来处理它,而不是程序方法。

您似乎也没有正确获取客户 ID - 至少根据您的 table 定义。我必须说,在您的审计中存储客户的名字非常奇怪 table。为什么不存储客户 ID?该名称不是唯一的,因此您没有提供可靠的审计线索。

create trigger claim_audits
on claims
for insert
as
begin
    set nocount on;

    insert into dbo.claim_audits (custname, amount, [action])
        select C.first_name, I.amount_of_claim, 'Updated customer claimed amount'
        from Inserted I
        inner join Customer_Policy CP on CP.id = I.customer_policy_id
        inner join Customer C on C.id = CP.customer_id;
end;

注意 - 您不想尝试 return 来自触发器的数据。

正如@Squirral 所指出的:amount_of_claim float:浮点数是一个近似值,不应该用于金钱。请改用小数或数字。