“for 循环”PL/SQL 的替代品

问题描述 投票:0回答:1

有什么方法可以在下面的示例中不使用循环吗? 这个想法是找到一种不使用循环的方法,并且当我有时减慢速度 更多数据。 从第一个表 param_tbl 中,我获取已填充的参数。 从第二个表 result_tbl i 根据第一个表的参数获取结果。
我将结果插入到第三个表 Final_table_resul_tbl 中。 但是使用循环我有太多延迟。 我尝试使用功能“WITH”和合并,但没有得到想要的结果。

    CREATE TABLE param_tbl (asset_id int, actual_date date  );

      insert into param_tbl (asset_id,actual_date)
      SELECT 1, DATE '2017-04-03' FROM DUAL UNION ALL
      SELECT 1, DATE '2019-02-25' FROM DUAL UNION ALL
      SELECT 1, DATE '2020-03-13' FROM DUAL UNION ALL
      SELECT 2, DATE '2017-11-02' FROM DUAL UNION ALL
      SELECT 2, DATE '2019-02-25' FROM DUAL UNION ALL
      SELECT 3, DATE '2016-12-31' FROM DUAL UNION ALL
      SELECT 3, DATE '2021-10-21' FROM DUAL UNION ALL
      SELECT 3, DATE '2022-10-19' FROM DUAL;
      

CREATE TABLE result_tbl (asset_id int,asset varchar2(30) , actual_date date  );
    
    insert into result_tbl (asset_id,asset,actual_date)
      SELECT 1,'Mixed',   DATE '2017-04-03' FROM DUAL UNION ALL
      SELECT 1,'Mixed'   ,DATE '2019-02-25' FROM DUAL UNION ALL
      SELECT 1,'Mixed',   DATE '2020-03-13' FROM DUAL UNION ALL
      SELECT 2,'Dividend Stocks' ,DATE '2017-11-02' FROM DUAL UNION ALL
      SELECT 2,'Dividend Stocks' ,DATE '2019-02-25' FROM DUAL UNION ALL
      SELECT 3,'Large Cap Stocks' ,DATE '2016-12-31' FROM DUAL UNION ALL
      SELECT 3,'Large Cap Stocks', DATE '2021-10-21' FROM DUAL UNION ALL
      SELECT 3,'Large Cap Stocks', DATE '2000-10-21' FROM DUAL UNION ALL
      SELECT 3,'Large Cap Stocks', DATE '2001-10-21' FROM DUAL UNION ALL
      SELECT 3,'Large Cap Stocks' ,DATE '2022-10-19' FROM DUAL;
      
 CREATE TABLE final_table_resul_tbl (asset_id int,asset varchar2(30) , actual_date date );
 

   declare 
   cursor c1 is

 select   asset_id,actual_date from param_tbl;
        BEGIN

            
    FOR a IN c1 LOOP
  insert into final_table_resul_tbl(asset_id,asset,actual_date) 

              select  asset_id,asset, actual_date from   result_tbl
              where asset_id = a.asset_id and  actual_date = a.actual_date;
              END loop;
END;
oracle plsql plsqldeveloper
1个回答
0
投票

将 PL/SQL 循环转换为 SQL 连接通常会显着提高性能并简化代码:

insert into final_table_resul_tbl2(asset_id,asset,actual_date) 
select result_tbl.asset_id, result_tbl.asset, result_tbl.actual_date
from param_tbl
join result_tbl
   on  param_tbl.asset_id = result_tbl.asset_id
   and param_tbl.actual_date = result_tbl.actual_date;

SQL版本不需要在SQL和PL/SQL引擎之间进行上下文切换。 SQL 版本允许优化器为连接选择可能更快的执行计划。例如,由于表上没有过滤器,优化器很可能会选择散列连接。而 PL/SQL 版本是硬编码的嵌套循环连接。对于大量数据,散列连接通常比嵌套循环连接快得多。

© www.soinside.com 2019 - 2024. All rights reserved.