【问题标题】:Efficient way of changing the query (a way to avoid unions)?更改查询的有效方法(避免联合的方法)?
【发布时间】:2020-11-25 19:54:09
【问题描述】:

我有两个存储过程和一个函数。从函数中获取价格后,我需要进行一些计算。我在最后使用 UNION 连接查询,但速度很慢。

PROCEDURE STORED_PROC1
(
    custId IN varchar2,
    param2 IN varchar2,
    param3      IN DATE,
    param4      IN DATE,
    ret_cd OUT VARCHAR2,
    results out t_cursor
) as
   sql_str VARCHAR2(10000);
   custCursor t_cursor;
   BEGIN
    sql_str := 'select qry.col1,qry.col2,qry.col3,qry.col4,qry.col5,qry.col6, qry.price, **qry.price*col5**
                    (select col1,col2,col3,col4,col5,col6, getPrice(col1,col2,col3,col4) as price from tableA, tableB where ....) qry'; 
    open results for sql_str;
   END STORED_PROC1;
   
FUNCTION getPrice ( col1 varchar2, col2 varchar2, col3 varchar2, col4 DATE) RETURN number AS total number;
    sql_str VARCHAR2(10000);
    BEGIN
      select price into total from tableB where ......
      return total;
    end;
    
PROCEDURE STORED_PROC2
(
    custId IN varchar2,
    param2 IN varchar2,
    param3      IN DATE,
    param4      IN DATE,
    custIds in varchar2;
    ret_cd OUT VARCHAR2,
    results out t_cursor
) as
  sql_str VARCHAR2(10000);
 
 
 loop 
 for each custId ...
    call STORED_PROC1
    create a dynamic sql.
 end loop.

execute the dynamic sql at the end. 

dynamic SQL at the end will be like this:

select qry.col1,qry.col2,qry.col3,qry.col4,qry.col5,qry.col6, qry.price, **qry.price*col5** from
                    (select col1,col2,col3,col4,col5,col6, getPrice(col1,col2,col3,col4) as price from tableA, tableB) qry
                    
UNION
select qry.col1,qry.col2,qry.col3,qry.col4,qry.col5,qry.col6, qry.price, **qry*price*col5** from
                    (select col1,col2,col3,col4,col5,col6, getPrice(col1,col2,col3,col4) as price from tableA, tableB) qry
                    
 UNION
 ............
  
  END STORED_PROC2;

So this query with UNION is working, but is very slow as the range expands. wanted to see if there is a better way to do this.

我使用 param1、param2、param3 和 param4 调用存储过程 STORED_PROC1。 此 STORED_PROC1 使用每行中的值调用 getPrice。 但 custIds 是单个 custId 的串联,用逗号分隔。 custIds = id1,id2,id3。所以我需要为每个调用这个 STORED_PROC1 客户 ID。

【问题讨论】:

  • 如果子查询不返回必须过滤掉的重复数据,我建议您使用 UNION ALL 而不是 UNION

标签: sql oracle plsql union


【解决方案1】:

好吧,也许你不必像你描述的那样做。为什么不立即计算价格,在STORED_PROC1 内?像这样的:

procedure stored_proc1 (param1,...,
                        results out t_cursor
                       )
is
begin
  open results for
    select col1, 
           col2, 
           ..., 
           getPrice(col1, col2, ...) as price         --> call the function here
    from tableA;
end;    

【讨论】:

  • 我无法正确地提出我的问题。但我现在更新了。
猜你喜欢
  • 1970-01-01
  • 2020-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多