Oracle物化视图语法,以及例子

create materialized view [view_name]
refresh [fast|complete|force]
[
on [commit|demand] |
start with (start_time) next (next_time)
]
as
{创建物化视图用的查询语句}


以上是Oracle创建物化视图(Materialized View,以下简称MV)时的常用语法,各参数的含义如下:

1.refresh [fast|complete|force] 视图刷新的方式:

   fast: 增量刷新.假设前一次刷新的时间为t1,那么使用fast模式刷新物化视图时,只向视图中添加t1到当前时间段内,主表变化过的数据.为了记录这种变化,建立增量刷新物化视图还需要一个物化视图日志表。create materialized view log on (主表名)。

   complete:全部刷新。相当于重新执行一次创建视图的查询语句。

   force: 这是默认的数据刷新方式。当可以使用fast模式时,数据刷新将采用fast方式;否则使用complete方式。

2.MV数据刷新的时间:

   on demand:在用户需要刷新的时候刷新,这里就要求用户自己动手去刷新数据了(也可以使用job定时刷新)

   on commit:当主表中有数据提交的时候,立即刷新MV中的数据;

   start ……:从指定的时间开始,每隔一段时间(由next指定)就刷新一次;


例子:

create materialized view MV_BASE_PD_CLAZZ
refresh complete on demand
start with to_date('08-05-2012 01:01:01', 'dd-mm-yyyy hh24:mi:ss') next SYSDATE + 1 
as 
select t.cls_id,
       t.cls_name,
       LPAD('|-', (level - 1) * 4, ' | ') || LPAD('『', 2) || t.cls_name ||
       RPAD('』', 2) tree_name,
       CONNECT_BY_ISLEAF IS_LEAF,
       level CLS_LEVEL,
       t.par_id,
       t1.cls_name par_name,
       t.root_id,
       t2.cls_name root_name,
       ltrim(sys_connect_by_path(t.cls_name, ','), ',') FULL_NAME,
       t.order_value,
       t.is_del
  from base_pd_class t
  left join base_pd_class t1 on t.par_id = t1.cls_id
  left join base_pd_class t2 on t.root_id = t2.cls_id
  where t.is_del = 0
 start with t.par_id = -1
connect by prior t.cls_id = t.par_id
order siblings by t.order_value desc