您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。