您好,登錄后才能下訂單哦!
在 PostgreSQL 中使用觸發器可以實現自動維護歷史記錄的功能。具體步驟如下:
CREATE TABLE user_history (
id SERIAL PRIMARY KEY,
user_id INT,
name VARCHAR(50),
email VARCHAR(50),
action VARCHAR(10),
action_timestamp TIMESTAMP
);
CREATE OR REPLACE FUNCTION log_user_history()
RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
INSERT INTO user_history(user_id, name, email, action, action_timestamp)
VALUES (NEW.id, NEW.name, NEW.email, 'INSERT', NOW());
ELSIF TG_OP = 'UPDATE' THEN
INSERT INTO user_history(user_id, name, email, action, action_timestamp)
VALUES (NEW.id, NEW.name, NEW.email, 'UPDATE', NOW());
ELSIF TG_OP = 'DELETE' THEN
INSERT INTO user_history(user_id, name, email, action, action_timestamp)
VALUES (OLD.id, OLD.name, OLD.email, 'DELETE', NOW());
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER user_history_trigger
AFTER INSERT OR UPDATE OR DELETE ON users
FOR EACH ROW
EXECUTE FUNCTION log_user_history();
現在,當對用戶表進行插入、更新或刪除操作時,觸發器會自動將歷史記錄插入到歷史記錄表中,從而實現自動維護歷史記錄的功能。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。