oracle - Copying a row in the same table (within a loop of array of tables) -
there great answer @shannonseverance on question
copying row in same table without having type 50+ column names (while changing 2 columns)
that showed how dynamically copy row within table same table (changing pk)
declare r table_name%rowtype; begin select * r table_name pk_id = "original_primary_key"; -- select pk_seq.nextval r.pk_id dual; -- 11g can use instead: r.pk_id := pk_seq.nextval; r.fk_id := "new_foreign_key"; insert table_name values r; end;
i apply approach within function called each time within array of table names
so can select using execute immediate - how declare 'r'? can replace 'table_name' in code variable passed function?
table(1)="table1"; table(2)="table2"; t 1..table.count loop copytablecontacts(table(i)); end loop;
tia
mike
in end, have amended function slightly
i build 2 arrays
1 - list of table names user_tab_columns table 2 - each table in array1, build comma delimited list of column names all_tab_columns table
so end 2 arrays (example...)
tablename(1) = 'member' tablename(2) = 'salary' tablecolumns(1) = 'id, surname, sex, dob' tablecolumns(2) = 'id, currentsal, bonus, grade'
i pass these 2 arrayvalues function , use dynamic sql during looping of tablename() array...
procedure copytablerow(inorigmemno number, innewmemno number, intablename user_tab_columns.table_name%type, intablestring long) selectstring varchar2(32000):=null; newtablestring long:=null; inserttablestring long:=null; sqlresultcount number:=0; begin /*check if there @ least 1 row copy*/ execute immediate 'select count(*) ' || intablename || ' id= ' || inorigmemno sqlresultcount; if sqlresultcount > 0 /*build insert statement each row returned*/ dbms_output.put_line('at least 1 row found on ' || intablename || '(' || sqlresultcount || ')'); newtablestring := replace(intablestring, 'id', 'replace(id, id,' || innewmemno || ')'); selectstring := 'select ' || newtablestring || ' ' || intablename || ' id = ' || inorigmemno; inserttablestring := 'insert ' || intablename || '(' || intablestring || ') (' || selectstring || ')'; end if;
i left insert statement based on table definition , value can execute
this seems work fine , suits current needs
note - works if each table has 1 row copy. next challenge cope of tables returning multiple rows id require copying (which interesting seeing i've painted myself non-cursor corner!)
mike
Comments
Post a Comment