[英]Creating a trigger to store an audit trail
我必须在 Claims 表上创建一个触发器,只要将新记录插入到 Claims 表中就会触发该触发器。 此触发器应存储客户名称和该客户的总amount_of_claim
。
Claim_audits(审计表)已经被创建。
架构:
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 应如下所示:
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伪表可以有 0-N 行,您需要处理它。 与 SQL 相关的任何事情一样,您应该使用基于集合的方法而不是程序方法来处理它。
您似乎也没有正确获取客户 ID - 至少根据您的表定义。 我必须说,将客户的名字存储在您的审计表中是非常奇怪的。 为什么不存储客户 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;
注意 - 您不想尝试从触发器返回数据。
正如@Squirral 所指出的: amount_of_claim float
:float 是一个近似值,不应该用于金钱。 请改用小数或数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.