在这里,我有两个表Customer_Account
和Cust_Transaction
,它们具有下面的属性,但没有太多细节,需要指出的是,表之间的关系是Account_ID
:
Cust_Account(
Account_ID PK,
Account_Name,
Account_Balance)
Cust_Transaction(
Trn_ID PK,
Trn_Date,
Trn_Amount,
Trn_Type,
Account_ID FK)
表中的数据如下:
|---------------------------------------|
|Account_ID|Account_Name|Account_Balance|
|---------------------------------------|
| 0001 | Ahmad | 0 |
|---------------------------------------|
|-----------------------------------------------|
|Trn_ID|Trn_Date |Trn_Amount|Trn_Type|Account_ID|
|---------------------------------------------- |
| 001 |01/01/20 | 4000 | Credit | 001 |
|-----------------------------------------------|
我想要一个解决方案,每当我使用以上数据输入Cust_Transaction
时,它还应将金额添加到他在Account_Balance
中的帐户,并且无论何时“提取”,都应减去{{ 1}}同时删除交易时,它也应减去Account_Balance
。
请以哪种方式解决我。
谢谢,
答案 0 :(得分:0)
您可以在交易表上创建TRIGGER,它会完美地处理表中的余额:
CREATE OR ALTER TRIGGER TR_Cust_Transaction ON Cust_Transaction
FOR INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON
UPDATE CA SET Account_Balance = ISNULL(Account_Balance,0) + ISNULL(I.Trn_Amount,0) - ISNULL(D.Trn_Amount,0)
FROM Cust_Account CA
LEFT JOIN (SELECT Account_Id, SUM(Trn_Amount * IIF(Trn_Type = 'Credit', 1, -1)) Trn_Amount FROM INSERTED GROUP BY Account_Id) I ON CA.Account_Id = I.Account_Id
LEFT JOIN (SELECT Account_Id, SUM(Trn_Amount * IIF(Trn_Type = 'Credit', 1, -1)) Trn_Amount FROM DELETED GROUP BY Account_Id) D ON CA.Account_Id = D.Account_Id
END
了解更多here。
提示:如果您永远不会在Cust_Transaction上插入/更新/删除多条记录,则可以直接连接到Inserted和Deleted表,而无需按account_id按数据分组。