- Trigger Function: inserted into a user data table, if the table data is useless, the field must be empty created_by; created_by the table data must not be empty.
- New functions during storage;
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$; - Add Trigger
-- DROP TRIGGER onadd ON public."user";
create trigger onadd before
insert
on
public."user" for each row execute procedure onaddfirst();
reference
PostgreSQL study manual (PL / pgSQL procedural language) - Stephen_Liu - blog Park
PostgreSQL functions (stored procedures) - PostgreSQL ™ Tutorials
PostgreSQL trigger - Ryan_zheng - blog Park