postgresql-根据字段长度内连接info_schema.columns选择记录

时间:2016-12-16 13:02:17

标签: sql postgresql pivot

我有两张桌子: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。 我可以这样做:

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中的行。感谢您对此问题的关注。

1 个答案:

答案 0 :(得分: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

它会给你一些字符串 &#34;插入myschema.table_2(tcol1,tcol2)从myschema.table_1中选择col1,col2,其中char_length(col1)&lt; = 5 AND char_length(col2)&lt; = 5&#34;你可以在EXECUTE命令或任何你想要的地方运行它。

我用CTE写的,所以所有部分都清晰可见。当然有很多方法可以把它写得更短等......: - )