oracle - 将行类型变量复制到另一个
问题描述
我有
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;
或类似的东西而不使用这些字段。
解决方案
如果这两个表具有相同的结构,那么至少从 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>
推荐阅读
- reactjs - 在 useEffect Hook 中选择一个 DOM 元素
- c - 无法以编程方式启动 Linux TAP 设备
- c# - Jetbrains Rider 无法解决符号 ServiceCollection
- python - 无效的参数/选项 - '|'
- git - bitbucket 连接失败
- javascript - 如果我需要添加更多卡片,如何使我的卡片独立,同时使代码可扩展?
- php - 如何在laravel网站上传视频并保存和列表
- python - Python pad list 是下一个乘数 6 的大小
- html - jQuery:小标签字体大小,如果字段不为空
- react-native - Redux-undo 在发布 apk 中返回未定义?