当表名、列名、列类型等底层表的信息发生改变的时候,就会使得视图无法使用,其时就需要对视图进行重新的编译。
第一步,查找失效的视图。
可以使用数据字典中的user_objects来查找出失效的视图名,还可以利用user_views来查找出相应视图的代码信息。
基本的代码如下:
----------------查找出失效的视图
Select object_name, ---------对象名称
object_type, ---------对象类型
status ---------对象当前状态
from user_objects ---------用户对象表
where object_type= ‘VIEW’
and status = ‘INVALID’;
----------------利用上面找出的试图名称,查找出视图的代码
Select VIEW_NAME, --------视图名称
TEXT --------视图的代码
from user_views --------用户视图表
where view_name=’view_name’
第二步,重新编译。
可以使用以下方式来重新编译视图:
ALTER VIEW view_name COMPILE;
如果视图的结构被改变了(如底层表的列被删除了),则上面的这种方法无法对视图重新编译成功。为此,现在只能把视图删掉,然后重新建立视图。
---------建立表和视图
create table table1
(
column1 integer,
column2 integer
);
create view view1 (column3) as
select column1 as column3 from table1;
---------查看修改前的状态
Select object_name,object_type,status
from user_objects
where object_type = 'VIEW' ;
and object_name='VIEW1';
--------修改前的状态为可用
OBJECT_NAME OBJECT_TYPE STATUS
------------ ---------- -------------
VIEW1 VIEW VALID
----------------修改table1中column1
alter table table1
modify column1 not null;
---------------再次查看修改后视图的状态,发现为“不可用”
Select object_name,object_type,status
from user_objects
where object_type = 'VIEW'
and object_name='VIEW1';
---------------修改后的状态
OBJECT_NAME OBJECT_TYPE STATUS
------------- --------- -------------
VIEW1 VIEW INVALID
---------------对视图进行重新编译
ALTER VIEW view1 COMPILE;
---------------再次查看视图的状态,视图“可用”
Select object_name,object_type,status
from user_objects
where object_type = 'VIEW'
and object_name='VIEW1';
OBJECT_NAME OBJECT_TYPE STATUS
----------- ---------- -----------
VIEW1 VIEW VALID
---------------如果破坏视图的结构,比如说删除column1,则以上的修复方式无效
alter table table1
drop column column1;
alter view view1 compile;
--重新编译无效,视图的结构已经改变
--------------删除原来的视图
drop view view1;
-------------查找出原来的视图语句,根据修改重新建立新的视图
Select VIEW_NAME,TEXT from user_views where view_name='VIEW1';
create view view1 as
select column2 from table1;
-------------查看视图的状态
Select object_name,object_type,status
from user_objects
where object_type = 'VIEW'
and object_name='VIEW1'
OBJECT_NAME OBJECT_TYPE STATUS
------------ ----------- -------------
VIEW1 VIEW VALID