2016-12-16 39 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寫了它,所以所有零件都清晰可見。當然,有些方法可以將它寫成更短的等等...... :-)