postgresql: Add triggers to the table

  1. 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.
  2. 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$;

     
  3. 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

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/HaruhiNo1/p/11795557.html