触发器——字符串数组循环插入表中

375 阅读1分钟
  1. 创建表

     DROP TABLE IF EXISTS es_table;
     CREATE TABLE es_table
     (
         id integer,
         province character varying(32) COLLATE pg_catalog."default" NOT NULL,
         modification_time timestamp without time zone DEFAULT now()
     )
     
     DROP TABLE IF EXISTS tokens;
     CREATE TABLE tokens
     (
         key character varying(32) COLLATE pg_catalog."default" NOT NULL
     )
    
  2. 创建函数:如果 province 不为空则,且内容是以英文逗号连接的字符串,将其按照逗号分隔成字符串数组,并循环插入 tokens 中

     create or replace function insert_to_token() returns trigger as $example_table$
     DECLARE s text[] ;
     begin
         if NEW.province is not null and NEW.province!='' then
             FOR idx IN 1..(array_length(string_to_array(NEW.province,','), 1)) loop
                 insert into tokens (key) values ((select string_to_array(NEW.province, ','))[idx]);
             end loop;
         end if;
         return NEW;
     end;
     $example_table$ language plpgsql;
    
  3. 创建触发器

     drop trigger insert_to_token on es_table;(可选)
     create trigger insert_to_token after insert or update on es_table for each row execute procedure insert_to_token();
    

4.插入数据测试效果,如果 tokens 表中有插入含有 wys、wyt、qq、wx 四条数据的行,证明触发器成功运行

	INSERT INTO es_table (province) VALUES ('wys,wyt,qq,wx');