[英]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.