試試這個:
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寫了它,所以所有零件都清晰可見。當然,有些方法可以將它寫成更短的等等...... :-)
爲此,您必須最有可能生成查詢字符串並使用'EXECUTE'運行它。如果你可以發佈兩個表的'CREATE TABLE'命令,我會看看它。因爲從描述我不確定結構。 – JosMac
已添加創建命令 – BenThomas
好的:-)我的意思是真正的表,但沒關係 - 請參閱答案... – JosMac