我有一个表,其中包含{service_id,service_name,region_name}
作为输入,我的过程获取service_id,即i_svc_region键,值对的列表,其中包含{service_name,region}。
如果记录不存在,则必须插入表中。我知道这是一个非常简单的查询。但是以下查询对性能没有影响吗?
哪个更好,为什么?
MERGE INTO SERVICE_REGION_MAP table1
USING
(SELECT i_svc_region(i).key as service_name,i_enabled_regions(i).value as region
FROM dual) table2
ON (table1.service_id =i_service_id and table1.region=table2.region)
WHEN NOT MATCHED THEN
INSERT (service_id,service_name ,region) VALUES (i_service_id ,table2.service_name,table2.region);
i_service_id-按原样传递。
MERGE INTO SERVICE_REGION_MAP table1
USING
(SELECT i_service_id as service_id, i_svc_region(i).key as service_name,i_enabled_regions(i).value as region
FROM dual) table2
ON (table1.service_id =table2.service_id and table1.region=table2.region)
WHEN NOT MATCHED THEN
INSERT (service_id,service_name ,region) VALUES (table2.service_id,table2.service_name,table2.region);
i_service_id被视为表中的列。
这真的有什么区别吗?
答案 0 :(得分:0)
您应该使用FORALL语句。这将导致性能比我们可以编写的任何循环快得多。查看文档,从https://docs.oracle.com/database/121/LNPLS/forall_statement.htm#LNPLS01321
开始答案 1 :(得分:0)
正如@Brian Leach建议的那样,FORALL将为您提供表中所有元素(i)的SQL引擎的一次往返。该 可以提高10到100倍,具体取决于表的大小和我以外的其他情况。
此外,您仅使用MERGE的INSERT功能,因此受时间尊敬的INSERT语句应使数据库的工作更加轻松/快捷。 MERGE有更多风吹草动,可以放慢脚步。
因此,请尝试以下操作:
FORALL i IN 1..i_svc_region(i).COUNT
INSERT INTO SERVICE_REGION_MAP table1
(service_id, service_name, region)
SELECT
i_service_id AS service_id,
i_svc_region(i).KEY AS service_name,
i_enabled_regions(i).VALUE AS region
FROM DUAL table2
WHERE NOT EXISTS
( SELECT *
FROM SERVICE_REGION_MAP table1
WHERE table1.service_id=table2.service_id AND table1.region=table2.region
);