在单个脚本中使用临时表执行多个指令

时间:2016-03-22 14:49:39

标签: oracle oracle11g

我尝试使用临时表优化选择查询(我更习惯使用SQL Server,所以可能有更好的方法)。

查询基本上是这个(稍微简化):创建表,填充表,使用它,删除表。

create global temporary table trucks (
    nb_trucks int,
    warehouse int
)
on commit preserve rows
;
insert into trucks (
    nb_trucks, warehouse
)
select
    sum(pla.NB_TRUCKS)
    ,pla.id_site
from ASI_MAS_PLA_PLANIFICATION pla
group by
    pla.id_site
;
select distinct
op.operation_id as OPERATION_CODE,
pla.id_site as WAREHOUSE_ID,
(
    select
    coalesce(sum(nb_trucks), 0)
    from trucks
    where
        and trucks.warehouse = pla.id_site
) as NB_TRUCKS,
from ASI_MAS_PLA_PLANIFICATION pla
inner join ASI_MAS_PLA_CL_PLANIF_OP op
    on op.planif_operation_id = pla.z_planif_operation_id
where
    pla.z_remainder = 0
group by
    op.operation_id
    ,pla.id_site
order by
    op.operation_id
;
truncate table trucks;
drop table trucks;

由于各种技术原因,我需要在一个脚本中执行这些操作(实际上我只需要执行“select”部分,但不使用临时表通过屋顶发送执行时间)。

我已将脚本放在begin ... end;块中,但它不喜欢我“创建”一个表作为第一条指令。

As I saw here,我目前正试图用“执行立即”like this来包装每个语句,但我不太喜欢这个解决方案。

如何在单个SQL脚本中执行多个语句,包括“create”?

1 个答案:

答案 0 :(得分:0)

没有解释计划很难理解。也许是"与"条款帮助:

WITH trucks AS
 (SELECT /*+ materialize */
   SUM(pla.nb_trucks) nb_trucks,
   pla.id_site warehouse
    FROM asi_mas_pla_planification pla
   GROUP BY pla.id_site)
SELECT DISTINCT op.operation_id AS operation_code,
                pla.id_site AS warehouse_id,
                (SELECT coalesce(SUM(nb_trucks), 0)
                   FROM trucks
                  WHERE trucks.warehouse = pla.id_site) AS nb_trucks
  FROM asi_mas_pla_planification pla
 INNER JOIN asi_mas_pla_cl_planif_op op
    ON op.planif_operation_id = pla.z_planif_operation_id
 WHERE pla.z_remainder = 0
 GROUP BY op.operation_id,
          pla.id_site
 ORDER BY op.operation_id;

但我认为查询逻辑存在一些问题。我认为你没有正确计算卡车。但你知道这是否正确。

也许这个查询更好?

SELECT op.operation_id AS operation_code,
       pla.id_site AS warehouse_id,
       nvl(SUM(pla.nb_trucks), 0) nb_trucks
  FROM (SELECT /*+ materialize*/ id_site,
               z_planif_operation_id,
               SUM(nb_trucks) nb_trucks
          FROM asi_mas_pla_planification
         WHERE z_remainder = 0
         GROUP BY id_site,
                  z_planif_operation_id) pla
 INNER JOIN asi_mas_pla_cl_planif_op op
    ON op.planif_operation_id = pla.z_planif_operation_id
 GROUP BY op.operation_id,
          pla.id_site
 ORDER BY op.operation_id;

此致