postgresql:给表添加触发器
- 触发器功能:向user表中插入一条数据,如果表中没用数据,则字段created_by必须为空;表中有数据则created_by必须不为空.
- 新建储存过程函数;
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$; - 添加触发器
-- 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 - 博客园