2016-12-16 38 views
0

我有两个表:1。 create table table_1(col1 text,col2 text) 2. create table table_2(tcol1 character varying(5), tcol2 character varying(5))。 table_1有50条记录,table_2是空的。如果table_2.tcol1 < = table_1.col1的长度和table_2.tcol2的长度< = table_1.col2的长度,我需要将这些记录从table_1加载到table_2。 我能做到这一点,如:postgresql-根据字段长度选择记录inner join information_schema.columns

insert into table_2(tcol1,tcol2) 
select col1,col2 from table_1 
where char_length(col1) <=5 and char_length(col2) <=5 

但在实际我有超过100列。有没有办法通过将table_1与information_schema.columns结合来实现此目的。这里的问题是table_1中的列是information_schema.columns中的行。感谢您对此问题的关注。

+0

为此,您必须最有可能生成查询字符串并使用'EXECUTE'运行它。如果你可以发布两个表的'CREATE TABLE'命令,我会看看它。因为从描述我不确定结构。 – JosMac

+0

已添加创建命令 – BenThomas

+0

好的:-)我的意思是真正的表,但没关系 - 请参阅答案... – JosMac

回答

0

试试这个:

with tab2cols as (select table_schema, table_name, column_name, character_maximum_length, ordinal_position from information_schema.columns where table_name = 'table_2' and ordinal_position > 0), 
tab1cols as (select table_schema, table_name, column_name, character_maximum_length, ordinal_position from information_schema.columns where table_name = 'table_1' and ordinal_position > 0), 
tab1sel as (select 'select '||string_agg(column_name,',' order by ordinal_position)||' from '||table_schema||'.'||table_name as select_string from tab1cols group by table_schema, table_name), 
tab2ins as (select 'insert into '||table_schema||'.'||table_name||' ('||string_agg(column_name,',' order by ordinal_position)||') 'as insert_string from tab2cols group by table_schema, table_name) 
select string_agg(_text, ' ') from (
    select insert_string as _text from tab2ins 
    union all 
    select select_string||' where ' as _text from tab1sel 
    union all 
    select string_agg('char_length('||t1.column_name||')<='||t2.character_maximum_length, ' AND ') as _text from tab2cols t2 join tab1cols t1 on t2.ordinal_position=t1.ordinal_position 
) a 

它会给你字符串如 “插入myschema.table_2(tcol1,tcol2)选择COL1,COL2从myschema.table_1其中CHAR_LENGTH(COL1)< = 5 AND CHAR_LENGTH (col2)< = 5“,您可以在EXECUTE命令或任何您想要的位置运行。

我用CTE写了它,所以所有零件都清晰可见。当然,有些方法可以将它写成更短的等等...... :-)