如何纠正我的 PostgreSQL 以纠正语法错误并很好地使用 CREATE TRIGGER 语句?

问题描述 投票:0回答:1

我需要创建一个 PostgreSQL PL/pgSQL 代码,能够模拟从一个账户到另一个账户的简单转账。 所以这是我的代码:

DROP TABLE clients, accounts, transactions;
 
CREATE TABLE IF NOT EXISTS clients
(
    id int PRIMARY KEY,
    name varchar
);
 
CREATE TABLE IF NOT EXISTS accounts
(
    id int PRIMARY KEY,
    balance float,
    client int,
    FOREIGN KEY (client) REFERENCES clients(id),
    CHECK (balance >= 0)
);
 
CREATE TABLE IF NOT EXISTS transactions
(
    id int PRIMARY KEY,
    payer int,
    recipient int,
    amount float,
    FOREIGN KEY (payer) REFERENCES clients(id),
    FOREIGN KEY (recipient) REFERENCES clients(id)
);
 
 
INSERT INTO clients VALUES (10, 'Client 1');
INSERT INTO clients VALUES (14, 'Client 2');
INSERT INTO clients VALUES (25, 'Client 3');
 
INSERT INTO accounts VALUES (2, 300, 10);
INSERT INTO accounts VALUES (8, 2000, 14);
INSERT INTO accounts VALUES (12, 650, 25);
 
 
 
 
CREATE TRIGGER new_transaction
AFTER INSERT ON transactions
BEGIN
    UPDATE accounts
    SET balance = balance - 50
    FROM clients
    WHERE clients.id = accounts.client AND clients.id = 10;
    UPDATE accounts
    SET balance = balance + 50
    FROM clients
    WHERE clients.id = accounts.client AND clients.id = 14;
END;
 
 
 
 
INSERT INTO transactions VALUES (1, 10, 14, 50);
SELECT * FROM accounts;

但是语法错误导致它无法工作...... 我尝试不使用 BEGIN 和 END 而是使用“FOR EACH STATMENT”,但它也出现了语法错误...... 你能帮我吗?

提前感谢您的回答!

postgresql triggers plpgsql
1个回答
0
投票

您需要创建一个函数来触发它;

CREATE OR REPLACE FUNCTION update_account_balance()
RETURNS TRIGGER AS $$
BEGIN
    -- amount from the payer's balance
    UPDATE accounts
    SET balance = balance - NEW.amount
    WHERE client = NEW.payer;

    -- amount to the recipient's balance
    UPDATE accounts
    SET balance = balance + NEW.amount
    WHERE client = NEW.recipient;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

然后通过

触发它
CREATE TRIGGER new_transaction
AFTER INSERT ON transactions
FOR EACH ROW
EXECUTE FUNCTION update_account_balance();

继续您的交易,它将自动触发交易表中的每一行插入。

© www.soinside.com 2019 - 2024. All rights reserved.