首页 > 解决方案 > 将行类型变量复制到另一个

问题描述

我有

l_tab1 table1%rowtype;
l_tab2 table2%rowtype;

table1 和 table2 的结构相同。

如何将数据从 l_tab1 移动到 l_tab2 ?

现在我可以看到两种方法,但我不喜欢它,因为我需要对字段进行硬编码。

1

l_tab2.field1 := l_tab1.field1;
l_tab2.field2 := l_tab1.field2;

2

select * into l_tab2
from table1
where field1 = l_tab1.field1
  and field2 = l_tab1.field2;

3

我相信它应该更容易像

insert into l_tab2
values l_tab1;

或类似的东西而不使用这些字段。

标签: oracleplsql

解决方案


如果这两个表具有相同的结构,那么至少从 Oracle 11.2 开始,一个简单的赋值就可以工作。

使用如下表

create table table1(col1 number, col2 number);
create table table2(col1 number, col2 number);

insert into table1 values (1, 11);
insert into table2 values (2, 22);

我们有:

SQL> select * from table1;

      COL1       COL2
---------- ----------
         1         11

SQL> select * from table2;

      COL1       COL2
---------- ----------
         2         22

SQL> declare
  2      l_tab1  table1%rowtype;
  3      l_tab2  table2%rowtype;
  4  begin
  5      select *
  6      into l_tab1
  7      from table1;
  8      l_tab2 := l_tab1;
  9      insert into table2 values l_tab2;
 10  end;
 11  /

PL/SQL procedure successfully completed.

SQL> select * from table2;

      COL1       COL2
---------- ----------
         1         11
         2         22

SQL>

推荐阅读