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

后端 未结 6 756
青春惊慌失措
青春惊慌失措 2021-01-31 09:35

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

相关标签:
6条回答
  • 2021-01-31 09:50

    You can create a 'temp' table, update two columns and do an insert-select from this 'temp' table.

    Eaxmple:

    create table temptemp as 
    select *
      from table_name
     where pk_id = "original_primary_key"
    
    update temptemp
    set col1 = ...
    ,   col2 =....
    
    insert into table2
    select * from temptemp;
    
    0 讨论(0)
  • 2021-01-31 09:52

    You could just query the data dictionary to generate the SQL for you.

    SELECT 'tbl.' || column_name || ','
    FROM   user_tab_columns
    WHERE  table_name = 'MYTABLE'
    ORDER BY column_id;
    

    Get the result of this query, paste into your SQL statement, adapt as necessary, and voila.

    0 讨论(0)
  • 2021-01-31 09:55

    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;
    
    0 讨论(0)
  • 2021-01-31 09:56

    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;
    
    0 讨论(0)
  • 2021-01-31 10:13

    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.

    0 讨论(0)
  • 2021-01-31 10:13

    You could make a simple stored procedure that take a table name and using the data dictionary writes the select statement text for you (the text of the select). Then copy, paste and Modify.

    0 讨论(0)
提交回复
热议问题