ITPub博客

首页 > 数据库 > Oracle > 在Oracle10g中使用包DBMS_ADVANCED_REWRITE实现新的查询重写功能

在Oracle10g中使用包DBMS_ADVANCED_REWRITE实现新的查询重写功能

原创 Oracle 作者:yaanzy 时间:2006-12-31 10:15:03 0 删除 编辑

从Oracle10g版本1开始,提供了新的包DBMS_ADVANCED_REWRITE来实现查询重写。它允许你截获特定的SQL语句,并将
其重定义为另一个SQL语句。下面是一个简单的例子:

1、确认测试用户有必要的权限去运行

CONN sys/password AS SYSDBA

GRANT EXECUTE ON DBMS_ADVANCED_REWRITE TO test;
GRANT CREATE MATERIALIZED VIEW TO test;

[@more@]

2、创建测试用表

CONN test/test

DROP TABLE rewrite_test_tab;

CREATE TABLE rewrite_test_tab (
id NUMBER,
description VARCHAR2(50),
CONSTRAINT rewrite_test_tab_pk PRIMARY KEY (id)
);

INSERT INTO rewrite_test_tab (id, description) VALUES (1, 'GLASGOW');
INSERT INTO rewrite_test_tab (id, description) VALUES (2, 'BIRMINGHAM');
INSERT INTO rewrite_test_tab (id, description) VALUES (3, 'LONDON');
COMMIT;

EXEC DBMS_STATS.gather_table_stats(USER, 'rewrite_test_tab');

3、查询测试表

SELECT * FROM rewrite_test_tab;

ID DESCRIPTION
---------- --------------------------------------------------
1 GLASGOW
2 BIRMINGHAM
3 LONDON

3 rows selected.

SQL>

4、创建要替换成的SQL使用的视图,然后将上面的语句重定义为查询这个视图

CREATE OR REPLACE VIEW rewrite_test_tab_v AS
SELECT id,
INITCAP(description) AS description
FROM rewrite_test_tab
ORDER BY description;

BEGIN
SYS.DBMS_ADVANCED_REWRITE.declare_rewrite_equivalence (
name => 'test_rewrite',
source_stmt => 'SELECT * FROM rewrite_test_tab',
destination_stmt => 'SELECT * FROM rewrite_test_tab_v',
validate => FALSE,
rewrite_mode => 'TEXT_MATCH');
END;
/

5、初始化参数QUERY_REWRITE_INTEGRITY缺省值为"enforced",意味只有原始语句的输出和替换后语句的输出完全
一致才会进行重写替换。而我们要实现替换后的输出跟原始输出是有差别的,所以需要将这个参数的值修改为
"TRUSTED"才行。

ALTER SESSION SET QUERY_REWRITE_INTEGRITY = TRUSTED;

Session altered.

SELECT * FROM rewrite_test_tab;

ID DESCRIPTION
---------- --------------------------------------------------
2 Birmingham
1 Glasgow
3 London

3 rows selected.

SQL>

6、视图[USER|ALL|DBA]_REWRITE_EQUIVALENCES中有这些重定义查询的相关信息

SELECT * FROM user_rewrite_equivalences;

OWNER NAME
------------------------------ ------------------------------
SOURCE_STMT
--------------------------------------------------------------------------------
DESTINATION_STMT REWRITE_MO
-------------------------------------------------------------------------------- ----------
TEST TEST_REWRITE
SELECT * FROM rewrite_test_tab
SELECT * FROM rewrite_test_tab_v TEXT_MATCH


1 row selected.

SQL>


更多的参考资料可见:

http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_advrwr.htm

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/3898/viewspace-887660/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
  • 博文量
    108
  • 访问量
    766864