码迷,mamicode.com
首页 > 数据库 > 详细

postgresql:给表添加触发器

时间:2019-11-07 09:23:05      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:integer   before   ret   logs   when   font   cannot   添加   new   

  1. 触发器功能:向user表中插入一条数据,如果表中没用数据,则字段created_by必须为空;表中有数据则created_by必须不为空.
  2. 新建储存过程函数;

    CREATE OR REPLACE FUNCTION public.onaddfirst()
     RETURNS trigger
     LANGUAGE plpgsql
    AS $function$
    DECLARE
        total integer;
    BEGIN
        SELECT count(*) INTO total FROM public.user;
        IF total != 0 THEN
            IF NEW.created_by IS NULL THEN
                RAISE EXCEPTION ‘created_by cannot be null‘;
            END IF;
        ELSE
            IF NEW.created_by  is not NULL THEN
                RAISE EXCEPTION ‘created_by must be null when you insert first user‘;
            END IF;
        END IF;
        RETURN NEW;
    END;
    $function$;

     
  3. 添加触发器

-- DROP TRIGGER onadd ON public."user";

create trigger onadd before
insert
    on
    public."user" for each row execute procedure onaddfirst();

 

参考

 PostgreSQL学习手册(PL/pgSQL过程语言) - Stephen_Liu - 博客园

 PostgreSQL函数(存储过程) - PostgreSQL教程™

 PostgreSQL 触发器 - Ryan_zheng - 博客园

 

 

 

 

 

 

 

postgresql:给表添加触发器

标签:integer   before   ret   logs   when   font   cannot   添加   new   

原文地址:https://www.cnblogs.com/HaruhiNo1/p/11795557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!