sql - PostgreSQL : CAST column only if exists -


os linux debian 5.3.1 if helps.

i have bunch of csv files managed import tables in postgresql. have same general layout (i.e. globally same columns), of them vary (i.e. of them may miss columns). clearer, general layout supposed columns a, b, c, d, e, table have colums a, b, d, e, other columns b, c, d, e...

i'd make general sql query changing type of columns (using cast) , import them in 1 single global table (t_import) columns a, b, c, d, e.

insert t_import (a, b, c, d, e)     select (       (cast integer) a,       (cast b character varying(14)) b,       (cast c integer) c,       (cast d character varying) d,       (cast e character varying) e     t_csv; 

however tables miss columns, should creating query each table want import, tiresome number of tables have.

is there way check if column exists in table want import, if exists, cast it, else use default value ? way allow me use same query different tables without getting errors.

globally i'd :

  • check if colum exists in table want import,
  • if column exists, cast in type want , use insert into,
  • if column doesn't exist, use default value insert still has insert , don't error message.

after many research still haven't found technical solution. struggle parameters if exists, exists, sub-queries... , can not manage this. there way or have wrong way @ problem ?

unite select queries providing defaults:

insert t_import (a, b, c, d, e)  select     a::integer,     b::character varying(14),     c::integer,     d::character varying,     e::character varying t_csv  union  select     null,     a,     null,     b,     c t2_csv 

notice columns passed insert command in order selected regardless of names , aliases.

from second united table on columns cast corresponding columns in first select not necessary explicitly cast.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -