2016-12-16 1 views
0

Ich habe zwei Tabellen: 1. create table table_1(col1 text,col2 text) 2. create table table_2(tcol1 character varying(5), tcol2 character varying(5)). Tabelle_1 hat 50 Datensätze und Tabelle_2 ist leer. Ich muss diese Datensätze von Tabelle_1 zu Tabelle_2 laden, wenn die Länge von table_2.tcol1 < = Länge von table_1.col1 und Länge von table_2.tcol2 < = Länge von table_1.col2. Ich kann diese wie tun:postgresql- wählen Datensätze basierend auf Feldlänge innere Verbindung 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 

Aber in der Praxis Ich habe mehr als 100 Spalten. Gibt es eine Möglichkeit, dies zu erreichen, indem Sie Tabelle_1 mit information_schema.columns verbinden. Das Problem hier ist Spalten in Tabelle_1 sind Zeilen in information_schema.columns. Vielen Dank für Ihr Interesse an dieser Frage.

+0

Dazu müssen Sie höchstwahrscheinlich eine Abfrage in eine Zeichenkette generieren und diese mit 'EXECUTE' ausführen. Wenn Sie 'CREATE TABLE' Befehle für beide Tabellen posten können, werde ich es mir ansehen. Weil ich von der Beschreibung über Strukturen nicht sicher bin. – JosMac

+0

habe create commands – BenThomas

+0

ok :-) Ich meinte echte Tabellen, aber macht nichts - siehe in der Antwort ... – JosMac

Antwort

0

versuchen Sie dies:

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 

Es wird Sie String wie „insert into myschema.table_2 (tcol1, tcol2) wählen col1, col2 von myschema.table_1 wo char_length (col1) < = 5 und char_length geben (col2) < = 5 ", die Sie in EXECUTE Befehl ausführen können oder wo immer Sie wollen.

Ich schrieb es mit CTE, so dass alle Teile deutlich sichtbar sind. Natürlich gibt es Wege, wie man es kürzer schreibt usw. :-)

Verwandte Themen