赞
踩
Oracle 23c 增强了 VALUES 子句的功能,它可以作为表值构造函数创建一组数据行(临时表),用于 SELECT、INSERT 以及 MERGE 语句。
这个新功能可以方便即席查询时精简代码,提高可读性。
我们首先创建一个简单的示例表:
create table t (
id integer not null primary key,
name varchar2(10),
amount integer
);
我们可以在 INSERT 语句中使用表值构造函数一次插入多行数据,例如:
insert into t(id, name, amount)
values (1, 'Apple', 100),
(2, 'Banana', 200),
(3, 'Cherry', 300);
select * from t;
ID|NAME |AMOUNT|
--+------+------+
1|Apple | 100|
2|Banana| 200|
3|Cherry| 300|
批量插入数据可以减少网络消耗,提高数据插入的性能。
在 Oracle 21c 以及之前的版本中,我们需要编写多个 INSERT 语句,或者使用 UNION ALL 将多行数据组成一个查询结果。例如:
insert into t(id, name, amount)
select 1, 'Apple', 100 from dual
union all
select 2, 'Banana', 200 from dual
union all
select 3, 'Cherry', 300 from dual;
SELECT 语句的 FROM 子句中也可以使用表值构造函数创建一个临时的结果集,此时我们需要为这个临时结果集指定表名和列名。例如:
select *
from (values
(1, 'Apple', 100),
(2, 'Banana', 200),
(3, 'Cherry', 300)
) s(id, name, amount);
ID|NAME |AMOUNT|
--+------+------+
1|Apple | 100|
2|Banana| 200|
3|Cherry| 300|
WITH 子句中同样可以使用表值构造函数创建一个临时表,例如:
with s(id, name, amount) as (
values
(1, 'Apple', 100),
(2, 'Banana', 200),
(3, 'Cherry', 300)
)
SELECT * FROM s;
ID|NAME |AMOUNT|
--+------+------+
1|Apple | 100|
2|Banana| 200|
3|Cherry| 300|
我们也可以使用表值构造函数为 MERGE 语句创建一个数据源表,例如:
merge into t using (values (1, 'Apple', 400), (2, 'Banana', 500), (3, 'Cheery', 600) ) s(id, name, amount) on (t.id = s.id) when matched then update set t.name = s.name, t.amount = s.amount when not matched then insert (t.id, t.name, t.amount) values (s.id, s.name, s.amount); select * from t; ID|NAME |AMOUNT| --+------+------+ 1|Apple | 400| 2|Banana| 500| 3|Cheery| 600|
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。