代码之家  ›  专栏  ›  技术社区  ›  Krishan Jangid

PostgreSQL-为可重新运行的插入脚本动态生成where not exists条件

  •  0
  • Krishan Jangid  · 技术社区  · 7 年前

    我需要在Postgres中为数据库中的所有表生成插入脚本,这样它就可以在不引发任何错误的情况下再次运行。 问题是,只有少数表具有主键,而其余表具有不同列的唯一索引。

    这就是为什么我不能列出创建唯一索引的列。 这背后的原因是模式是通过magnolia自动创建的。

    是否有人可以帮助我根据主键/唯一列编写生成insert语句的查询,其中包括“Where not exists(select 1 from table where column=value)”条件?

    2 回复  |  直到 7 年前
        1
  •  0
  •   Gordon Linoff    7 年前

    你可以用 on conflict :

    insert into t ( . . . )
        values ( . . . )
        on conflict do nothing;
    
        2
  •  0
  •   Krishan Jangid    7 年前

    此函数返回数据的插入脚本,并适用于主约束不可用的表。 我修改了在另一个线程上找到的代码,将条件添加到该线程中。

    CREATE OR REPLACE FUNCTION public.generate_inserts(varSchema text, varTable text) RETURNS TABLE(resultado text) AS $$
    
    DECLARE CODE TEXT;
    
    BEGIN
    CODE :=
    (
    SELECT
    'SELECT ''INSERT INTO '
    || table_schema || '.'
    || table_name ||' ('
    || replace(replace(array_agg(column_name::text)::text,'{',''),'}','') || ') SELECT ''||'
    || replace(replace(replace(array_agg( 'quote_nullable(' || column_name::text || ')')::text,'{',''),'}',''),',',' || '','' || ')
    || ' || '' Where Not Exists (Select 1 From ' || table_name ||' Where 1 = 1 ' 
    || ''''
    || replace(replace(replace(replace(array_agg(' || '' and (' || column_name::text || ' = '' || quote_nullable(' || column_name::text || '),' || ' || '' or ' || column_name::text || ' is null)''')::text,'{',''),'}',''),'"',''),',','')
    || '|| '');'''
    || ' FROM ' || table_schema || '.' || table_name || ';'
    FROM information_schema.columns c 
    WHERE table_schema = varSchema
    AND table_name = varTable
    GROUP BY table_schema, table_name);
    
    
    
    RETURN QUERY
    EXECUTE CODE;
    END;
    $$ LANGUAGE plpgsql;
    
    推荐文章