简体   繁体   English

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

[英]Creating a trigger to store an audit trail

I have to create a trigger on the Claims table that is triggered whenever a new record is inserted into the Claims table.我必须在 Claims 表上创建一个触发器,只要将新记录插入到 Claims 表中就会触发该触发器。 This trigger should store the customer name and the total amount_of_claim by that customer.此触发器应存储客户名称和该客户的总amount_of_claim

Claim_audits (audit table) have already been created. Claim_audits(审计表)已经被创建。

Schema:架构:

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)

Output should look like this: Output 应如下所示:

customer_name   amount_of_claim
abhinav         195000

This is what I have tried:这是我尝试过的:

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

The Inserted pseudo-table can have 0-N rows, and you need to handle that. Inserted伪表可以有 0-N 行,您需要处理它。 And as with anything SQL related you should approach it using a set-based approach - not a procedural approach.与 SQL 相关的任何事情一样,您应该使用基于集合的方法而不是程序方法来处理它。

You also don't appear to have been obtaining the customer id correctly - at least based on your table definitions.您似乎也没有正确获取客户 ID - 至少根据您的表定义。 I must say, its very odd to be storing the first name of the customer in your audit table.我必须说,将客户的名字存储在您的审计表中是非常奇怪的。 Why not store the customer id?为什么不存储客户 ID? The name is not unique, so you haven't provided a reliable audit trail.该名称不是唯一的,因此您没有提供可靠的审计跟踪。

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;

Note - you do not want to be attempting to return data from a trigger.注意 - 您不想尝试从触发器返回数据。

And as pointed out by @Squirral: amount_of_claim float : float is an approximate value and should never be used for money.正如@Squirral 所指出的: amount_of_claim float :float 是一个近似值,不应该用于金钱。 Use decimal or numeric instead.请改用小数或数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM