繁体   English   中英

客户账户余额如何影响 SQL 服务器中的客户交易表?

[英]How does Customer Account Balance affects from Customer Transaction Table in SQL Server?

在这里,我有两个表Customer_AccountCust_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中将金额添加到他/她的帐户中,并且每当它是“提款”时,它应该从Account_Balance减去,同时当交易删除时,它也应该从Account_Balance减去. 请帮助我应该以哪种方式解决它。 谢谢,

您可以在 transactions 表上创建 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 

在这里了解更多。

提示:如果您永远不会在 Cust_Transaction 上插入/更新/删除多条记录,您可以直接加入 Inserted 和 Deleted 表,无需按 account_id 按数据分组。

暂无
暂无

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

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