试试这个:
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