由于视图就是存储在数据库中的SQL,因此对于大部分视图而言,返回结果是固定的。但是利用一些变量可以创建动态结果的视图。
最简单的例子就是Oracle的数据字典视图,比如USER_DB_LINKS。
对于USER_DB_LINKS视图的定义的固定的,但是每个用户访问得到的结果是不同的,就是由于USER_DB_LINKS视图中使用了变量:
SQL> select text
2 from dba_views
3 where view_name = 'USER_DB_LINKS';
TEXT
--------------------------------------------------------------------------------
select l.name, l.userid, l.password, l.host, l.ctime
from sys.link$ l
where l.owner# = userenv('SCHEMAID')
由于使用了USERENV函数获取SCHEMAID信息,使得不同的用户登陆获得的方案ID不同,从而使得不同的用户访问USER_DB_LINKS视图获得的结果不同。
这里可以利用USER模仿一个类似的例子:
SQL> create table t_user
2 as select *
3 from dba_users;
Table created.
SQL> create view my_user
2 as select *
3 from t_user
4 where username = user;
View created.
SQL> grant select on my_user to public;
Grant succeeded.
SQL> show user
USER is "TEST"
SQL> select username, account_status
2 from my_user;
USERNAME ACCOUNT_STATUS
------------------------------ --------------------------------
TEST OPEN
SQL> conn / as sysdba
Connected.
SQL> show user
USER is "SYS"
SQL> select username, account_status
2 from test.my_user;
USERNAME ACCOUNT_STATUS
------------------------------ --------------------------------
SYS OPEN
SQL> conn u1/u1
Connected.
SQL> select username, account_status
2 from test.my_user;
USERNAME ACCOUNT_STATUS
------------------------------ --------------------------------
U1 OPEN
除了USER变量之外,还可以使用类似SYSDATE之类的变量来重建动态视图:
SQL> create table t_date
2 (id number,
3 time date);
Table created.
SQL> insert into t_date
2 select rownum, sysdate + rownum/86400
3 from dba_objects;
70858 rows created.
SQL> commit;
Commit complete.
SQL> create view v_date
2 as select *
3 from t_date
4 where time = sysdate;
View created.
SQL> alter session set nls_date_format = 'yyyy-mm-dd hh24:mi:ss';
Session altered.
SQL> select * from v_date;
ID TIME
---------- -------------------
43 2009-08-17 16:40:53
SQL> select * from v_date;
ID TIME
---------- -------------------
48 2009-08-17 16:40:58
SQL> select * from v_date;
ID TIME
---------- -------------------
55 2009-08-17 16:41:05
除了这些变量外,还可以利用DBMS_RANDOM包来构造动态的结果:
SQL> create table t_id (id number);
Table created.
SQL> insert into t_id
2 select rownum
3 from dba_objects
4 where rownum <= 10000;
10000 rows created.
SQL> commit;
Commit complete.
SQL> create view v_random as
2 select * from t_id
3 where id =
4 (select round(dbms_random.value(1, 10000)) from dual);
View created.
SQL> select * from v_random;
ID
----------
8258
SQL> select * from v_random;
ID
----------
3827
SQL> select * from v_random;
ID
----------
7970
SQL> select * from v_random;
ID
----------
6750
合理的利用这些变量创建视图,可以建立很多有趣的对象。