Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a row in the same table without having to type the 50+ column names (while changing 2 columns)

Tags:

sql

oracle

During my job, I usually have to copy rows while changing their primary key and giving them a new stamp and maybe changing the foreign key.

The problem is I don't want to type all the column names while doing;

insert into table_name
select pk_seq.nextval, 
       'foreign-key', 
       col3,
       col4...col51
  from table_name
 where pk_id = "original_primary_key"

And if i do * in the select statement i won't be able to update the first 2 columns...

Is there any way to do how I want to do it?

like image 409
Tolga E Avatar asked Sep 23 '10 16:09

Tolga E


3 Answers

Well it may not be much less verbose, but this PL/SQL is an option:

begin
  for r in (select *
              from table_name
             where pk_id = 'original_primary_key')
  loop
    r.pk := pk_seq.nextval;
    r.fk := 'foreign-key';
    insert into table_name values r;
  end loop;
end;
like image 165
Tony Andrews Avatar answered Nov 15 '22 13:11

Tony Andrews


Based on Tony's answer:

We know that at most one row will be returned since we are searching on primary key. And assuming that a valid key value is specified, at least one row will be returned. So we don't need the loop:

declare
    r table_name%ROWTYPE;
begin
    select *
    into r
    from table_name
    where pk_id = "original_primary_key";
-- 
    select pk_seq.nextval into r.pk_id from dual;
     -- For 11g can use instead: r.pk_id := pk_seq.nextval;
    r.fk_id := "new_foreign_key";
    insert into table_name values r;
end;
like image 15
Shannon Severance Avatar answered Nov 15 '22 13:11

Shannon Severance


Sorry - it's an all or nothing affair.
There isn't anything between SELECT * and list the specific columns, it's one or the other.

like image 3
OMG Ponies Avatar answered Nov 15 '22 13:11

OMG Ponies