89244553 2019-11-07
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 - 博客园