1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu ORACLE8i- P23 ppt

40 262 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Oracle8i Data Warehousing Features
Trường học Sybex, Inc.
Chuyên ngành Database Management
Thể loại Giáo trình
Năm xuất bản 2002
Thành phố Alameda
Định dạng
Số trang 40
Dung lượng 426,23 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Here are some examples of altering Mviews:ALTER MATERIALIZED VIEW mv_emp_date_aggPCTFREE 10 PCTUSED 60STORAGE NEXT 100k; ALTER MATERIALIZED VIEW mv_emp_date_aggADD PARTITION p5 VALUES LE

Trang 1

Here are some examples of altering Mviews:

ALTER MATERIALIZED VIEW mv_emp_date_aggPCTFREE 10

PCTUSED 60STORAGE (NEXT 100k);

ALTER MATERIALIZED VIEW mv_emp_date_aggADD PARTITION p5 VALUES LESS THAN (‘2003’)TABLESPACE data_2002;

ALTER MATERIALIZED VIEW mv_emp_date_aggDISABLE QUERY REWRITE;

When you want to get rid of an Mview that you’ve created, it’s as simple as usingthe DROP MATERIALIZED VIEW command Appendix E has the syntax for this com-mand, and you’ve already seen it used here in this chapter

DROP MATERIALIZED VIEW mv_emp_date_agg;

As you might expect, if you want to drop an Mview in a schema other than yourown, you need the DROP ANY MATERIALIZED VIEW privilege

“But I Already Have Aggregate Tables!”

So, you were ahead of the curve, and you already have a warehouse full of tables thatact like materialized views Oracle rewards you by allowing you to create an Mview on

an existing table To do this, you use the ON PREBUILT TABLE clause of the CREATEMATERIALIZED VIEW command

There are a few rules to follow for using existing aggregate tables:

• The number of columns and column names in the table must match those in thequery used in the CREATE MATERIALIZED VIEW command

• The table must be in the same schema as the materialized view being created

• The table must have the same name as the materialized view being created

Note: Keep in mind that the Mview you create with the ON PREBUILT TABLE clause will

replace the table of the same name Thus, that table will be converted into an Mview

Trang 2

Here’s an example of use of the ON PREBUILT TABLE clause:

Create the table that we will convert to a MVCREATE TABLE emp_agg as

SELECT TO_CHAR(hiredate,’yyyy’) Hireyear,COUNT(*) “Number Hired”

FROM EMPGROUP BY TO_CHAR(hiredate,’yyyy’);

Table created

Now, convert this into a MV using the ON PREBUILT TABLE clause

Note the name of the Mview is the same as the prebuilt table name

CREATE MATERIALIZED VIEWemp_agg

ON PREBUILT TABLEREFRESH COMPLETE ON DEMANDENABLE QUERY REWRITEAS

SELECT TO_CHAR(hiredate,’yyyy’) Hireyear,COUNT(*) “Number Hired”

FROM EMPGROUP BY TO_CHAR(hiredate,’yyyy’);

Data Dictionary Views for Mviews

Several data dictionary views are provided for use with Mviews They’re listed in Table 19.3

TABLE 19.3: MVIEW DATA DICTIONARY VIEWS

DBA_MVIEWS General information on materialized views in the

Trang 3

TABLE 19.3: MVIEW DATA DICTIONARY VIEWS (CONTINUED)

ALL_REFRESH_DEPENDENCIES The last refresh information for objects on which

Mviews are dependent

DBA_MVIEW_ANALYSIS Detailed information on Mviews, such as last refresh

time and SCN

DBA_MVIEW_DETAIL_RELATIONS Mviews and their dependent base tables

DBA_MVIEW_JOINS Information on join conditions within Mviews DBA_MVIEW_KEYS Various information on Mview relationships For use

with DBA_MVIEW_DETAIL_RELATIONS to get moredetails on Mview relationships

There are two refresh options:

• REFRESH ON COMMIT causes the Mview to be refreshed upon the COMMIT ofany transaction that is changing the underlying base tables of the view

• REFRESH ON DEMAND delays the refresh of the materialized view until a house refresh job is executed We will discuss warehouse refresh later in thischapter

ware-You also need to select the refresh method to be used by Oracle when actually

refreshing the view There are five refresh method choices, each with its own userestrictions: FAST, COMPLETE, FORCE, NEVER, and ALWAYS

Let’s take a closer look at the refresh options and refresh methods

Mview Refresh Options

As mentioned, two refresh options are made available when you create a materializedview You can also alter an Mview to change its refresh option

Trang 4

Refresh on Demand

The REFRESH ON DEMAND option of the CREATE MATERIALIZED VIEW command

is the default refresh option for any Mview created

Mview Refresh Methods

The various refresh methods can be a bit confusing—in particular fast refresh and plete refresh Here we’ll examine their functionality and the rules associated with them

com-Fast Refresh

A fast refresh, also known as an incremental refresh, causes only the changed rows in

the Mviews to be changed Only rows that contain aggregates based on the changedrows of the base view will be changed in the Mview Fast refresh is probably the bestoption, but there are a number of restrictions on it

If you wish to do a fast refresh of your Mview upon commitment of changes to thebase table, an associated Mview log must be created on the base table To do this, usethe CREATE MATERIALIZED VIEW LOG command, and in the WITH clause definewhich columns you want to track in the log In order to fast refresh the Mview, youmust include the columns involved in the primary key of the base table (More infor-mation on Mview logs can be found later in this chapter.)

Here are the general rules for employing fast refresh:

• The tables in the FROM clause cannot be views

• Mviews cannot contain nonrepeating expressions such as SYSDATE orROWNUM, or nonrepeating PL/SQL functions

• LONG RAW and LONG data types are not supported for fast refresh

• You cannot use the HAVING and CONNECT BY clauses

• The WHERE clause can only contain inner and outer equijoins All joins must

be connected with ANDs

• Fast refresh does not support subqueries, inline views, or use of the UNION,UNION ALL, INTERSECT, or MINUS operations

MATERIALIZED VIEWS

Beyond Simple Database Management

P A R T

III

Trang 5

The restrictions on use of fast refresh depend on the type of Mview They are as follows:

columns of the GROUP BY clause

• An aggregate function is not required, but if one is used it can only include

the following: SUM, COUNT(column), COUNT(DISTINCT column),

COUNT(*), AVG, VARIANCE, STDDEV, MIN, and MAX

• There may be other restrictions You may well be able to use the fast refreshmethod, but still have to refresh on demand

NOTE You cannot perform fast refreshes for updates to base tables of Mviews that tain joins and aggregates Fast refreshes are only possible for operations that add data tothe Mview using direct load operations (for example, direct load path SQL*Loader imports

con-or INSERTS using the APPEND hint)

com-mit) is allowed with this type of view Restrictions include the following:

• The SELECT list must contain all GROUP BY columns

• You can use expressions in the SELECT and GROUP BY columns, but theexpressions must be the same in both columns

• In a single-table Mview to be fast refreshed, the WHERE clause is not ported

sup-• A COUNT(*) must be included in the Mview SELECT list

• The MIN and MAX functions are not supported

• An Mview log must exist and must contain all columns to be referenced inthe Mview You must include the INCLUDING NEW VALUES clause of theMview log

• If the AVG or SUM function is used, you must also use the COUNT functionand include the same expression in the COUNT function as the AVG orSUM function For example if you include a SUM(pay), you’ll also need toinclude a COUNT(pay) in the query of the Mview

Trang 6

any GROUP BY clauses

• If the WHERE clause contains outer joins, unique constraints must exist onthe join columns of the inner join table

• The ROWIDs of all the tables in the FROM list must appear in the SELECTlist within the query defining the Mview

• You must have an Mview log on each base table of the Mview, and the logsmust contain the ROWIDs of the base tables

Complete Refresh

If you choose complete refresh, your Mview will be completely rebuilt rather than justupdated with the incremental changes to the base tables Often, this is the onlyrefresh method available for use Its benefits include the fact that you don’t need tocreate a snapshot (Mview) log from the base tables of the Mview The drawback, how-ever, is that the underlying table of the Mview is truncated before the refresh, and sothere are no rows in the view until the refresh completes

Force Refresh

Using the Force method tells Oracle that a fast refresh is the preferred method ofupdating the view, but to do a complete refresh if a fast refresh is not possible

Always and Never

Always causes an unconditional refresh of the materialized view, and Never presses the refresh altogether

sup-The Data Warehouse Refresh Facility (DBMS_MVIEW)

If your Mviews cannot be set to REFRESH ON COMMIT (which means they are set toREFRESH ON DEMAND), then you need another method of updating the Mviews thatyou have in your system This is the purpose of the Warehouse Refresh facility of Oracle8i, which is present in the form of the DBMS_MVIEW package

The DBMS_MVIEW package contains a number of different procedures, but for thepurposes of refreshing Mviews we are interested in the following:

• DBMS_MVIEW.REFRESH, which refreshes a specific Mview

• DBMS_MVIEW.REFRESH_ALL_MVIEWS, which refreshes all Mviews

• DBMS_MVIEW.REFRESH_DEPENDENT, which refreshes all Mviews that aredependent on one or more base tables

MATERIALIZED VIEWS

Beyond Simple Database Management

P A R T

III

Trang 7

NOTE The DBMS_MVIEW package is also used to manage remote Mview updates SeeChapter 25 for more information on simple replication with Mviews.

Setting Up DBMS_MVIEW

The primary consideration for setting up the Warehouse Refresh facility is properlysetting up the Oracle Job Scheduler Table 19.4 lists the parameters that you need toconfigure and their purpose Once you have set these parameters, you are ready torefresh the Mviews

TABLE 19.4: JOB SCHEDULER PARAMETERS PERTINENT TO DBMS_MVIEW

Parameter Name Default Value Description

JOB_QUEUE_PROCESSES 0 Determines the number of job queue

processes that Oracle will start when thedatabase starts Each queue is capable ofrunning one job at a time Thus, if multiplequeues are started, you can run refreshes

in parallel

JOB_QUEUE_INTERVAL 60 Determines the amount of time (in

sec-onds) that will elapse before a job queueprocess looks for another job to execute.UTL_FILE_DIR None Defines external directories that can be

written to by the UTL_FILE procedure

N OTE JOB_QUEUE_PROCESSES is dynamically modifiable using the ALTER SYSTEMcommand Changing the other parameters requires bouncing the database

Using DBMS_MVIEW.REFRESH

The REFRESH procedure of the DBMS_MVIEW command is an overloaded procedure.This is to allow the DBA to pass in either a single table or a comma-delimited list oftables for refresh This procedure has the following definitions:

Argument Name Type In/Out Default? - - - -

Trang 8

LIST VARCHAR2 INMETHOD VARCHAR2 IN DEFAULTROLLBACK_SEG VARCHAR2 IN DEFAULTPUSH_DEFERRED_RPC BOOLEAN IN DEFAULTREFRESH_AFTER_ERRORS BOOLEAN IN DEFAULTPURGE_OPTION BINARY_INTEGER IN DEFAULTPARALLELISM BINARY_INTEGER IN DEFAULTHEAP_SIZE BINARY_INTEGER IN DEFAULTATOMIC_REFRESH BOOLEAN IN DEFAULT

Argument Name Type In/Out Default?

- - - TAB TABLE OF VARCHAR2(227) IN/OUT

-METHOD VARCHAR2 IN DEFAULTROLLBACK_SEG VARCHAR2 IN DEFAULTPUSH_DEFERRED_RPC BOOLEAN IN DEFAULTREFRESH_AFTER_ERRORS BOOLEAN IN DEFAULTPURGE_OPTION BINARY_INTEGER IN DEFAULTPARALLELISM BINARY_INTEGER IN DEFAULTHEAP_SIZE BINARY_INTEGER IN DEFAULTATOMIC_REFRESH BOOLEAN IN DEFAULT

Note that most of these parameters have default values, so in many cases you’llonly need to provide the table (or list of tables) to update and then the update methodyou wish to use Table 19.5 describes the parameters for the REFRESH procedure

TIP Often the DBA will create a job (using the DBMS_JOBS package) in the Job uler to automate the execution of DBMS_MVIEW.REFRESH See Chapter 20 for more infor-mation on DBMS_JOBS

Sched-TABLE 19.5: DBMS_MVIEW.REFRESH PARAMETERS

Refresh Parameter Purpose

LIST A comma-delimited list of Mviews to refresh

MATERIALIZED VIEWS

Beyond Simple Database Management

P A R T

III

Trang 9

TABLE 19.5: DBMS_MVIEW.REFRESH PARAMETERS (CONTINUED)

Refresh Parameter Purpose

METHOD The refresh method to use: A=Always, F=Fast, ?=Force, and

C=Complete

ROLLBACK_SEG The name of a specific rollback segment to use when performing

the refresh

PUSH_DEFERRED_RPC Set to TRUE always; used for updateable snapshots and has no

effect with warehouse-based Mviews

REFRESH_AFTER_ERRORS Indicates whether the job should continue refreshing other

Mviews if an error is encountered with any previous Mviewrefresh Set to TRUE to continue the job

PURGE_OPTION Set to FALSE always

PARALLELISM Set to 0 always

ATOMIC_REFRESH If TRUE, all refreshes are in one transaction If False, all refreshes

are in their own transaction

Listing 19.4 is an example of running DBMS_MVIEW.REFRESH

Listing 19.4: Using DBMS_MVIEW.REFRESH

Query the existing view Note that we have 14 records

SQL> SELECT empno, ename FROM EMP;

EMPNO ENAME - -

Trang 10

7934 MILLER

14 rows selected

Query the associated Mview SQL> SELECT * FROM emp_agg;

HIRE Number Hired

-1980 1

1981 10

1982 2

1983 1

Add a new record SQL> INSERT INTO emp VALUES (8000,’FREEMAN’,’KING’,NULL, SYSDATE, 4000,2000,10); 1 row created SQL> commit; Note, the Mview is not updated SQL> SELECT * FROM emp_agg; HIRE Number Hired

-1980 1

1981 10

1982 2

1983 1

Use the warehouse refresh facility to update the Mview

SQL> BEGIN

2 DBMS_MVIEW.REFRESH(‘EMP_AGG’,’A’);

3 END;

4 / PL/SQL procedure successfully completed

Now, look at the Mview, it’s updated!

SQL> SELECT * FROM emp_agg;

MATERIALIZED VIEWS

Beyond Simple Database Management

P A R T

III

Trang 11

HIRE Number Hired

-1980 1

1981 10

1982 2

1983 1

2001 1

Using DBMS_MVIEW.REFRESH_ALL_MVIEWS Of course, you’re likely to need a procedure that just refreshes all Mviews that are in need of refreshing The REFRESH_ALL_MVIEWS procedure fits the bill This procedure will refresh all stale snapshots (ones that have pending updates from the base tables) Argument Name Type In/Out Default? - - - -NUMBER_OF_FAILURES BINARY_INTEGER OUT

METHOD VARCHAR2 IN DEFAULT ROLLBACK_SEG VARCHAR2 IN DEFAULT REFRESH_AFTER_ERRORS BOOLEAN IN DEFAULT ATOMIC_REFRESH BOOLEAN IN DEFAULT

The parameters of the REFRESH_ALL_MVIEWS procedure are consistent with the parameters shown in Table 19.5 for the REFRESH procedure Also, note that most of these parameters do have default values, so the only parameter you need to send to the procedure is the first one (which is an OUT type, so be careful there!)

Listing 19.5 is an example of the use of DBMS_MVIEW.REFRESH_ALL_MVIEWS

Listing 19.5: Using DBMS_MVIEW.REFRESH_ALL_MVIEWS

DECLARE Failures BINARY_INTEGER;

BEGIN DBMS_MVIEW.REFRESH_ALL_MVIEWS(failures);

DBMS_OUTPUT.PUT_LINE(‘Procedure had ‘||failures||’ failures.’);

END;

/ Procedure had 0 failures

PL/SQL procedure successfully completed

Using DBMS_MVIEW.REFRESH_DEPENDENT

Often, you’ll know about changes to a given base table that may potentially affect many Mviews This can occur, for example, after a load process has added data to the table The REFRESH_DEPENDENT procedure of DBMS_MVIEW allows you to refresh all Mviews that are based on one or more updated dependent tables This procedure

Trang 12

refreshes all Mviews that have not already been refreshed Like the DBMS_MVIEW.REFRESH procedure, REFRESH_DEPENDENT is overloaded This allows you to pass inone or several tables to the procedure for refresh

Argument Name Type In/Out Default?

- - - NUMBER_OF_FAILURES BINARY_INTEGER OUT

-LIST VARCHAR2 INMETHOD VARCHAR2 IN DEFAULTROLLBACK_SEG VARCHAR2 IN DEFAULTREFRESH_AFTER_ERRORS BOOLEAN IN DEFAULTATOMIC_REFRESH BOOLEAN IN DEFAULT

Argument Name Type In/Out Default?

- - - NUMBER_OF_FAILURES BINARY_INTEGER OUT

-TAB -TABLE OF VARCHAR2(227) INMETHOD VARCHAR2 IN DEFAULTROLLBACK_SEG VARCHAR2 IN DEFAULTREFRESH_AFTER_ERRORS BOOLEAN IN DEFAULTATOMIC_REFRESH BOOLEAN IN DEFAULT

Listing 19.6 is an example of the REFRESH_DEPENDENT procedure

Listing 19.6: Using DBMS_MVIEW.REFRESH_DEPENDENT

DECLAREFailures BINARY_INTEGER;

BEGINDBMS_MVIEW.REFRESH_DEPENDENT(failures, ‘EMP,DEPT’);

DBMS_OUTPUT.PUT_LINE(‘Procedure had ‘||failures||’ failures.’);

END;

/PL/SQL procedure successfully completed

Mview Logs

Fast (incremental) refreshes depend heavily upon the presence of an Mview log If

you want to be able to fast refresh an Mview, you must create an Mview log on each base table that is a part of that materialized view These Mview logs (also called snap-

shot logs) record each change that occurs to the base table They are read during the

Mview refresh process so that the view can be properly updated without having toscan all the tables on which the view is based

MATERIALIZED VIEWS

Beyond Simple Database Management

P A R T

III

Trang 13

Creating Mview Logs

To create an Mview log, use the CREATE MATERIALIZED VIEW LOG command Aswith any other schema object that will store information, you can define the storagecharacteristics of the Mview log with the STORAGE clause You can also define thetablespace that will store the Mview log, as well as the logging characteristics

When you create an Mview log, you use the WITH clause to define how the Mviewstores the changes to its base table Options available for designating storage of thechange information include ROWID, Primary Key (the default) or both the ROWIDand primary key In addition, you can specify a list of columns to be recorded in theMview All columns referenced in the Mview definition query must be referenced inthe Mview log

The INCLUDING NEW VALUES clause, which is required for a fast refresh, is anoptional part of the Mview log This clause causes both the old and new values of thechanged rows to be stored in the Mview log The default, EXCLUDING NEW VALUESwill cause the new values not to be stored

To create an Mview log in a schema that is not your own, you must have the lowing privileges:

fol-• CREATE ANY TABLE

• CREATE ANY TRIGGER

• SELECT (on the underlying master table)

• COMMENT ANY TABLEFollowing is an example of the SQL used to create an Mview log:

CREATE MATERIALIZED VIEW LOG ON building_incomeTABLESPACE users

NOLOGGINGWITH PRIMARY KEY, ROWIDINCLUDING NEW VALUES;

Altering and Dropping Mview Logs

Often you will need to modify the STORAGE clause, modify the partitioning strategy

in some way, or change the default degree of parallelism Perhaps, through the use ofthe ADD clause, you want to alter the Mview log so that it starts storing the primarykey Maybe you need to modify the list of columns to be stored in the Mview Log.This is all facilitated through the use of the SQL command ALTER MATERIALIZEDVIEW LOG

Trang 14

N OTE The ADD clause of ALTER MATERIALIZED VIEW LOG only adds items to berecorded in the Mview log, such as the ROWID or an additional list of columns If anything

is to be removed from the Mview, the view itself must be dropped and re-created

The same grants are required for modifying an Mview log as are required to create it

Here’s an example of this command; see Appendix E for complete syntax:

ALTER MATERIALIZED VIEW LOG ON EMPADD ROWID;

Sometimes you just need to drop the Mview log because it’s not being used more Sometimes you need to drop it because you want to change the nature of what

any-is being stored in the log In either case, use the DROP MATERIALZED VIEW LOGcommand to remove the log

If the Mview log is not in your schema, you must have the DROP ANY TABLE privilege

Here’s an example of this simple command; see Appendix E for syntax

DROP MATERIALIZED VIEW LOG ON EMP;

Data Dictionary Views of Mview Logs

To query information on Mview logs from the data dictionary, Oracle has the SHOT_LOGS (DBA, ALL, and USER) These views provide information such as theMview log owner, the view name, the SQL text that makes up the view, and a greatdeal of additional information

*_SNAP-The DBA_SNAPSHOT_LOG_FILTER_COLS view provides a list of the columns onwhich the snapshot logs are built

NOTE There is no synonym created for the DBA_SNAPSHOT_LOG_FILTER_COLS view Ifyou need to reference it from a schema other than SYS, you must prefix the view with theSYS schema

Dimensions

The purpose of a dimension in Oracle is clearly reflected in its name: A dimension is

used to define the hierarchical nature of data In other words, a dimension defines a

DIMENSIONS

Beyond Simple Database Management

P A R T

III

Trang 15

parent-child relationship between the columns in your tables This information isused by the optimizer to enable certain query rewrite operations (see Table 19.1).Although dimensions are an optional feature of materialized views in Oracle8i, youmust use them if you want these query rewrite operations to function.

An example of a dimension would be a time relationship among various data ments An employee’s pay, for instance, might be divided into several linear elements:Lifetime Pay, Yearly Pay, Quarterly Pay, Monthly Pay, Weekly Pay, and the Hourly PayRate Within a data warehouse, you might have a table called PAY_TABLE, and withinthat table you’d have the employee’s ID and net or gross pay (among other things).You could then create an Mview that contains columns based on these linear ele-ments (LIFETIME_PAY, YEARLY_PAY, QUARTERLY_PAY, and so on) This Mview, oncecreated, would speed up management queries on pay information, and providing aneasy way to drill up or down through the various pay levels

ele-With the table and the Mview created, you would then create a dimension todefine the time relationships for the Oracle optimizer Then, when you query the basetable using an aggregate function, such as summing the pay by quarter, the dimen-sion helps the optimizer to determine whether the Mview can be used instead of thebase table This informed decision is made possible because the dimension defines therelationships between hourly, weekly, and yearly pay

Creating a Dimension

So, this new dimension stuff sounds great, you say, and you want to try it You bly won’t be surprised to find that the command for creating a dimension is the CREATE DIMENSION command Also not surprisingly, you need the CREATE DIMEN-SION privilege to create a dimension in your own schema, and the CREATE ANYDIMENSION privilege to create one in any other schema You must also have at leastSELECT privileges on the objects referenced in the dimension And, of course, theobjects must already exist

proba-Defining the Dimension

When you issue the CREATE DIMENSION command (see Appendix E for the plete syntax), you will proceed to define three different elements for the dimension:

com-• The LEVEL clause

• The HIERARCHY clause

• The ATTRIBUTE clause

Trang 16

dimension If the dimension consists of a single table it is called a normalized

dimension; if it consists of two or more tables, it is called a denormalized dimension.

Each level can be named and can consist of up to 32 columns from one tableonly To allow incorporation of multiple tables in the dimension, you can definemultiple LEVELs Within the LEVEL clause, you will assign each column to agiven identifier name that will be referenced when defining the dimension’sHIERARCHY Also, a given column can only exist in a single dimension

NOTE There are some restrictions when you assign multiple tables to a dimension

First, you must have foreign key relationships established between the tables of thedimensional HIERARCHY All columns defined in the dimension should be defined as NOTNULL The NOT NULL requirement is required but not enforced

LEVELs, creating the actual hierarchy You start by listing the most atomic level asdefined in the LEVEL clause (such as Hourly Pay) and move to the most encom-passing level of the hierarchy (such as Lifetime Pay) Thus, each subsequent level

of the hierarchy is a child of the preceding level of the hierarchy Another example

of a hierarchy would be a City, State, and Country relationship You would startcreating the HIERARCHY with the City, and work your way up to Country

Within the HIERARCHY clause is a JOIN clause that defines the join relationship ofthe various columns in the dimension

NOTE As in the LEVEL clause, NULLs in the table columns are not recommended for theHIERARCHY clause They can cause incorrect results to be returned (no error will be gener-ated, however) Each child key in the HIERARCHY must join with a parent-level column

one-to-one relationships between an attribute and other dimensional attributes;

for example, in a hierarchy of Cubicle, Office, Floor, and Building In the Cubiclelevel, there is also a one-to-one relationship between the Office and the Employeewho occupies the Cubicle In the Office (which in our example can take up part

of a Floor), there is a relationship between the Office and the Person who signed

DIMENSIONS

Beyond Simple Database Management

P A R T

III

Trang 17

the lease on that Office In the Building, there is a Manager, so we have a one relationship there as well Each of these relationships could be defined for agiven dimension in the ATTRIBUTE clause Finally, you can include multiple hier-archies and attributes in a single dimension.

one-to-In sum, here are the fundamental rules for creating and defining a dimension:

• A parent dimension can have one or more children

• A child dimension can have only one parent

• The relationship between a dimensional HIERARCHY level and any dependentATTRIBUTEs must be one-to-one only

• Columns of each HIERARCHICY level must be NOT NULL

• A column of a HIERARCHY cannot be associated with more than one dimension

• You cannot create cyclical hierarchical relationships

A Dimension Example

Listing 19.7 provides an extended example of the creation of a dimension In thisexample, we will create a materialized view that has multiple base tables This Mviewwill also be created using inline views As a result, this is the most complicated Mviewcreated in this chapter

After creating the Mview, we create a dimension on the columns of the Mview.This dimension has two hierarchies:

• A HIERARCHY for the rollup of the rents paid to the Management Company ofseveral buildings What are the LEVELs? The rents are paid at the Office level.The business rules say that a given Office can exist on only one Floor and thatyou may have multiple Offices on each Floor Thus, we have a one-to-many rela-tionship between Floors and Offices Again, each Floor is assigned to a givenBuilding and a given Floor may exist in only one Building (but the same Floor

ID may be used in multiple Buildings) The rollup is then from Office to Floor toBuilding, and that hierarchy is defined in the first LEVEL

• The second HIERARCHY is from the Floor Agent who is responsible for ing the rents on a given Floor, to the Building Manager who is responsible formanaging the Building

collect-Finally, the dimension relates the ATTRIBUTEs of the Floor number to the FloorAgent, and the Building number to the Building Manager

After creating the dimension, we query the base table of the Mview and find thatindeed, our query has been rewritten

Trang 18

Listing 19.7: Creating a Dimension

Note: The account in which you will be running this code

must have been granted GLOBAL QUERY REWRITE privileges directly, not through a role If your account does not have this privilege, remove the ENABLE QUERY REWRITE line from the CREATE

MATERIALIZED VIEW command, and it will work

DROP MATERIALIZED VIEW mv_building_income;

DROP TABLE building_income;

DROP TABLE floor_agent;

DROP TABLE building_manager;

DROP DIMENSION building_dim;

CREATE TABLE building_income(

today_date DATE,office_number NUMBER,floor_number NUMBER,building_number NUMBER,rent_paid NUMBER,floor_agent NUMBER,building_manager NUMBER,CONSTRAINT pk_building_income PRIMARY KEY(today_date, office_number, floor_number, building_number)USING INDEX TABLESPACE index_tbs

STORAGE (INITIAL 10K NEXT 10K) );

CREATE TABLE floor_agent( floor_agent NUMBER,agent_name varchar2(40) );

CREATE TABLE building_manager( building_manager NUMBER,manager_name varchar2(40) );

Need to create an mview log

INSERT INTO floor_agent VALUES(1, ’Franks, Peter’);

INSERT INTO floor_agent VALUES

DIMENSIONS

Beyond Simple Database Management

P A R T

III

Trang 19

ANALYZE TABLE building_income COMPUTE STATISTICS;

This is a complex Mview, so it cannot refresh fast

CREATE MATERIALIZED VIEWmv_building_incomeBUILD IMMEDIATEREFRESH COMPLETE ON DEMANDENABLE QUERY REWRITEAS

SELECT TRUNC(a.today_date) todays_date,a.building_number,

a.floor_number,SUM(a.floor_total) todays_floor,SUM(b.building_total) todays_buildingFROM

(SELECT TRUNC(today_date) as today_date,building_number, floor_number, SUM(rent_paid) as floor_totalfrom building_income

GROUP BY today_date, building_number, floor_number) a,(SELECT TRUNC(today_date) as today_date, building_number,SUM(rent_paid) as building_total

FROM building_income

Trang 20

GROUP BY today_date, building_number) bWHERE a.today_date=b.today_dateAND a.building_number=b.building_numberGROUP BY trunc(a.today_date), a.building_number, a.floor_number;

CREATE DIMENSION building_dimLEVEL office is building_income.office_numberLEVEL floor is building_income.floor_numberLEVEL building is building_income.building_numberLEVEL floor_agent is building_income.floor_agentLEVEL building_manager is building_income.building_managerHIERARCHY floor_rollup

(office CHILD OFfloor CHILD OFbuilding

)HIERARCHY management_rollup(

floor_agent CHILD OFbuilding_manager)

ATTRIBUTE floor DETERMINES building_income.floor_agentATTRIBUTE building DETERMINES building_income.building_manager;

ANALYZE TABLE mv_building_income COMPUTE STATISTICS;

exec DBMS_OLAP.VALIDATE_DIMENSION(‘BUILDING_DIM’,’SCOTT’,TRUE,TRUE);

PL/SQL procedure successfully completed

SELECT * FROM mview$_exceptions;

Ngày đăng: 26/01/2014, 19:20

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w