| Oracle® Database Administrator's Guide 10g Release 1 (10.1)< /strong> Part Number B10739-01 |
|
|
View PDF |
This chapter describes schema object manage ment issues that are common across multiple types of schema objects. The following topics are presented:
You can crea
te several tables and views and grant privileges in one operation using the CREATE SCHEMA statement. The CREATE SC
HEMA statement is useful if you want to guarantee the creation of several tables, views, and grants in one operation. If an in
dividual table, view or grant fails, the entire statement is rolled back. None of the objects are created, nor are the privileges gra
nted.
Specifically, the CREATE SCHEMA statement can include only CREATE TABLE, CREATE
VIEW, and GRANT statements. You must have the privileges necessary to issue the included statements. You are not
actually creating a schema, that is done when the user is created with a CREATE USER statement. Rather, you are populat
ing the schema.
The following statement creates two tables and a view that joins data from the two tables:
CREATE SCHEMA AUTHORIZATION scott
CREATE TABLE dept (
deptno NUMBER(3,0) PRIMARY KEY,
dname VARCHAR2(1
5),
loc VARCHAR2(25))
CREATE TABLE emp (
empno NUMBER(5,0) PRIMARY KEY,
ename VARCHAR2(15) NOT NULL,
job VARCHAR2(10),
mgr NUMBER(5,0),
hiredate DATE DEFAULT (sysdate),
sal NUMBER(7,2),
comm NUMBER(
7,2),
deptno NUMBER(3,0) NOT NULL
CONSTRAINT dept_fkey REFERENCES dept)
CREATE VIEW sales_staff AS
SELECT
empno, ename, sal, comm
FROM emp
WHERE deptno = 30
WITH CHECK OPTION CONSTRAINT sales_staff_cnst
GRAN
T SELECT ON sales_staff TO human_resources;
The CREATE SCHEMA statement does not support Oracle Database ext
ensions to the ANSI CREATE TABLE and CREATE VIEW statements, including the STORAGE clause.
|
See Also: Oracle Database SQL Reference for synta x and other information about theCREATE SCHEMA statement |
You analyze a schema object (table, index, or cluster) to:
Collect and manage statistics for it
Verify the validity of its storage format
Identify migrated and chained rows of a table or cluster
Note:
Do not use theCOMPUTE and <
code>ESTIMATE clauses of ANALYZE to collect optimizer statistics. These clauses are supported for backward compat
ibility. Instead, use the DBMS_STATS package, which lets you collect statistics in parallel, collect global statistics f
or partitioned objects, and fine tune your statistics collection in other ways. The cost-based optimizer, which depends upon statisti
cs, will eventually use only statistics that have been collected by DBMS_STATS. See PL/SQL Packages and Types Reference for more information on the DBMS_
STATS package.
You must use the ANALYZE statement (rather than DBMS_STATS) for statistics collec
tion not related to the cost-based optimizer, such as:
To use the VALIDATE or LIST CHAINED ROWS clauses
To collect information on freelist blocks
The following topics are discussed in this section:
You can use the DBMS_STATS package or the ANALYZE statement to gather statistics
about the physical storage characteristics of a table, index, or cluster. These statistics are stored in the data dictionary and can
be used by the optimizer to choose the most efficient execution plan for SQL statements accessing analyzed objects.
Oracle rec
ommends using the more versatile DBMS_STATS package for gathering optimizer statistics, but you must use the ANALY
ZE statement to collect statistics unrelated to the optimizer, such as empty blocks, average space, and so forth.
The < code>DBMS_STATS package allows both the gath ering of statistics, including utilizing parallel execution, and the external manipulation of statistics. Statistics can be stored in tables outside of the data dictionary, where they can be manipulated without affecting the optimizer. Statistics can be copied betwe en databases or backup copies can be made.
The following DBMS_STATS procedures enable the gathering of optimizer
statistics:
GATHER_INDEX_STATS
GATHER_TABLE_STATS
GATHER_SCHEMA_STATS
GATHER_DATABASE_STATS
|
See Also:
|
To verify the integrity of the structure of a table, index, cluster, or materialized view, use the ANALYZE statement wi
th the VALIDATE STRUCTURE option. If the structure is valid, no error is returned. However, if the structure is corrupt,
you receive an error message.
For example, in rare cases such as hardware or other system failures, an index can become corru pted and not perform correctly. When validating the index, you can confirm that every entry in the index points to the correct row of the associated table. If the index is corrupt, you can drop and re-create it.
If a table, index, or cluster is corrupt, you s hould drop it and re-create it. If a materialized view is corrupt, perform a complete refresh and ensure that you have remedied the p roblem. If the problem is not corrected, drop and re-create the materialized view.
The following statement analyzes the
emp table:
ANALYZE TABLE emp VALIDATE STRUCTURE;
You can validate an object and all related objects (for example, indexes) by including the CASCADE option. The fol
lowing statement validates the emp table and all associated indexes:
ANALYZE TABLE emp VAL IDATE STRUCTURE CASCADE;
You can specify that you want to perform structure vali
dation online while DML is occurring against the object being validated. There can be a slight performance impact when validating wit
h ongoing DML affecting the object, but this is offset by the flexibility of being able to perform ANALYZE online. The f
ollowing statement validates the emp table and all associated indexes online:
ANALYZE TABL E emp VALIDATE STRUCTURE CASCADE ONLINE;
You can look at t
he chained and migrated rows of a table or cluster using the ANALYZE statement with the LIST CHAINED<
/code> ROWS clause. The results of this statement are stored in a specified table created explicitly to accept the infor
mation returned by the LIST CHAINED ROWS clause. These results are useful in determining wheth
er you have enough room for updates to rows. For example, this information can show whether PCTFREE is set appropriately
for the table or cluster.
To create the table to ac
cept data returned by an ANALYZE ... LIST CHAINED ROWS statement, execute the UTLCHAIN.SQL or UTLCHN1.SQL script. These
scripts are provided by the database. They create a table named CHAINED_ROWS i
n the schema of the user submitting the script.
CHAINED_ROWS table is dependent upon the
compatibility level of your database and the type of table you are analyzing. See the Oracle Database SQL Reference for more information. |
|
See Also: Oracle Database Reference for a description of theCHAINED_ROWS table |
You can use the information in the CHAINED_ROWS table to reduce or eliminate migrated and chained rows in an existing table. Use the following procedure.
Use the ANALYZE statement to collect information about migrated and chained rows.
ANALYZE TABLE order_hist LIST CHAINED ROWS;
Query the output table:
SE LECT * FROM CHAINED_ROWS WHERE TABLE_NAME = 'ORDER_HIST'; OWNER_NAME TABLE_NAME CLUST... HEAD_ROWID TIMESTAMP ---------- ---------- -----... ------------------ --------- SCOTT ORDER_HIST ... AAAAluAAHAAAAA1AAA 04-MAR-96 SCOTT ORDER_ HIST ... AAAAluAAHAAAAA1AAB 04-MAR-96 SCOTT ORDER_HIST ... AAAAluAAHAAAAA1AAC 04-MAR-96
The output li sts all rows that are either migrated or chained.
If the output table shows that you have many migrated or chained r ows, then you can eliminate migrated rows by continuing through the following steps:
Create an intermediate table wi th the same columns as the existing table to hold the migrated and chained rows:
CREATE TABLE int_order
_hist
AS SELECT *
FROM order_hist
WHERE ROWID IN
(SELECT HEAD_ROWID
FROM CHAINED_ROWS
WHERE TABLE_NAME = 'ORDER_HIST');
Delete the migrated and chained rows from the existing table:
DELETE FROM order_hist
WHERE ROWID IN
(SELECT HEAD_ROWID
FROM CHAINED_ROWS
WHERE TABLE_NAM
E = 'ORDER_HIST');
Insert the rows of the intermediate table into the existing table:
INSERT INTO order_hist SELECT * FROM int_order_hist;
Drop the intermediate table:
DROP TABLE int_order_history;
Delete the information collected in step 1 from the output table:
DELETE FROM CHAINED_ROWS WHERE TABLE_NAME = 'ORDER_HIST';
Use the ANALYZE
code> statement again, and query the output table.
Any rows that appear in the output table are chained. You can eli
minate chained rows only by increasing your data block size. It might not be possible to avoid chaining in all situations. Chaining i
s often unavoidable with tables that have a LONG column or long CHAR or VARCHAR2 columns.
You can delete all rows of a table or all rows in a group of clustered tables so that the table (or cluster) still exists, but is completely empty. For example, consider a table that contains monthly data, and at the end of each month, you need to empty it (delete all rows) after arch iving its data.
To delete all rows from a table, you have the following options:
Use the DE
LETE statement.
Use the DROP and CREATE statements.
Use the TRUNCATE statement.
These options are discussed in the following sections
You can delete the rows of a table using the DELETE statement. For example, the following statement deletes
all rows from the emp table:
DELETE FROM emp;
If there are many rows present i
n a table or cluster when using the DELETE statement, significant system resources are consumed as the rows are deleted.
For example, CPU time, redo log space, and undo segment space from the table and any associated indexes require resources. Also, as
each row is deleted, triggers can be fired. The space previously allocated to the resulting empty table or cluster remains associated
with that object. With DELETE you can choose which rows to delete, whereas TRUNCATE and DROP
affect the entire object.
You can drop a table and then re-create
the table. For example, the following statements drop and then re-create the emp table:
D ROP TABLE emp; CREATE TABLE emp ( ... );
When dropping and re-creating a table or cluster, all associated indexes, integr ity constraints, and triggers are also dropped, and all objects that depend on the dropped table or clustered table are invalidated. Also, all grants for the dropped table or clustered table are dropped.
You can delete all rows of the table using the TRUNCATE statement. For example, the fol
lowing statement truncates the emp table:
TRUNCATE TABLE emp;
Using the
TRUNCATE statement provides a fast, efficient method for deleting all rows from a table or cluster. A TRUNCATE st
atement does not generate any undo information and it commits immediately. It is a DDL statement and cannot be rolled back. A T
RUNCATE statement does not affect any structures associated with the table being truncated (constraints and triggers) or autho
rizations. A TRUNCATE statement also specifies whether space currently allocated for the table is returned to the contai
ning tablespace after truncation.
You can truncate any table or cluster in your own s
chema. Any user who has the DROP ANY TABLE system privilege can truncate a table or cluster in any schema.
Before truncating a table or clustered table containing a parent key, all referencing foreign keys in different tables must be disabled. A self-referential constraint does not have to be disabled.
As a TRUNCATE statement deletes rows from a table, trig
gers associated with the table are not fired. Also, a TRUNCATE statement does not generate any audit information corresp
onding to DELETE statements if auditing is enabled. Instead, a single audit record is generated for the TRUNCATE
code> statement being issued. See the Oracle Database Security
Guide for information about auditing.
A hash cluster cannot be truncated, nor can tables within a hash or index clust
er be individually truncated. Truncation of an index cluster deletes all rows from all tables in the cluster. If all the rows must be
deleted from an individual clustered table, use the DELETE statement or drop and re-create the table.
The REUSE STORAGE or DROP STORAGE o
ptions of the TRUNCATE statement control whether space currently allocated for a table or cluster is returned to the con
taining tablespace after truncation. The default option, DROP STORAGE, reduces the number of extents allocated to the re
sulting table to the original setting for MINEXTENTS. Freed extents are then returned to the system and can be used by o
ther objects.
Alternatively, the REUSE STORAGE option specifies that all space currently allocated for the table
or cluster remains allocated to it. For example, the following statement truncates the emp_dept cluster, leaving all ext
ents previously allocated for the cluster available for subsequent inserts and deletes:
TRUNCATE CLUSTE R emp_dept REUSE STORAGE;
The REUSE or DROP STORAGE option also applies to any associated index
es. When a table or cluster is truncated, all associated indexes are also truncated. The storage parameters for a truncated table, cl
uster, or associated indexes are not changed as a result of the truncation.
|
See Also: Oracle Database SQL Reference for syntax and other information about theTRUNCATE TABLE and TRUNCATE C
LUSTER statements |
Database triggers are proced ures that are stored in the database and activated ("fired") when specific conditions occur, such as adding a row to a table. You can use triggers to supplement the standard capabilities of the database to provide a highly customized database management system. For example, you can create a trigger to restrict DML operations against a table, allowing only statements issued during regular business hours.
Database triggers can be associated with a table, schema, or database. They are implicitly fired when:
DML statements are executed (INSERT, UPDATE, DELETE) against an associated table
Certain DDL statements are executed (for example: ALTER, CREATE, DROP
code>) on objects within a database or schema
A specified database event occurs (for example: STAR
TUP, SHUTDOWN, SERVERERROR)
This is not a complete list. See the Oracle Database SQL Reference for a full list of statements and database events that cause triggers to fire
Create triggers with the CREATE TRIGGER statement.
They can be defined as firing BEFORE or AFTER the triggering event, or INSTEAD OF it. The fol
lowing statement creates a trigger scott.emp_permit_changes on table scott.emp. The trigger fires before an
y of the specified statements are executed.
CREATE TRIGGER scott.emp_permit_changes
BEFORE
DE
LETE OR INSERT OR UPDATE
ON scott.emp
.
.
.
pl/sql block
.
.
.
You can later
remove a trigger from the database by issuing the DROP TRIGGER statement.
A trigger can be in either of two dist inct modes:
Enabled
An enabled trigger executes its trigger body if a triggering statement is iss ued and the trigger restriction, if any, evaluates to true. By default, triggers are enabled when first created.
Disabled
A disabled trigger does not execute its trigger body, even if a triggering statement is issued and the trigg er restriction (if any) evaluates to true.
To enable or disable triggers us
ing the ALTER TABLE statement, you must own the table, have the ALTER object privilege for the table, or ha
ve the ALTER ANY TABLE system privilege. To enable or disable an individual trigger using the ALTER TRIGGER
statement, you must own the trigger or have the ALTER ANY TRIGGER system privilege.
|
See Also:
|
You enable a disabled trigger using the ALTER TRIGGER statement with the ENABLE option. To enable the disab
led trigger named reorder on the inventory table, enter the following statement:
ALTER TRIGGER reorder ENABLE;
To enable all triggers defined for a specific
table, use the ALTER TABLE statement with the ENABLE ALL TRIGGERS option. To enable all triggers defined fo
r the INVENTORY table, enter the following statement:
ALTER TABLE inventory
ENABLE ALL
TRIGGERS;
|
See Also: Oracle Database SQL Reference< /a> for syntax and other information about theALTER TRIGGER statement |
Consi der temporarily disabling a trigger if one of the following conditions is true:
An object that the trigg er references is not available.
You must perform a large data load and want it to proceed quickly withou t firing triggers.
You are loading data into the table to which the trigger applies.
You disable a trigger using the ALTER TRIGGER statement with the DISABLE option. To disable the trigger reorder on the inventory table, enter the following statement:
ALTER TRIGGER reorder DISABLE;
You can disable all trigger
s associated with a table at the same time using the ALTER TABLE statement with the DISABLE ALL TRIGGERS op
tion. For example, to disable all triggers defined for the inventory table, enter the following statement:
ALTER TABLE inventory
DISABLE ALL TRIGGERS;
Integrity constraints are rules that restrict the values f
or one or more columns in a table. Constraint clauses can appear in either CREATE TABLE or ALTER TABLE stat
ements, and identify the column or columns affected by the constraint and identify the conditions of the constraint.
This sect ion discusses the concepts of constraints and identifies the SQL statements used to define and manage integrity constraints. The foll owing topics are contained in this section:
Modifying, Renaming, or Dropping Existing Integrity Constraints
Viewing Constraint Information
|
See Also:
|
You can specify that a constraint is enabled (ENABLE) or disabled (DISABLE). If a constraint is enabled, data is checked as it is entered or updated in the database, and
data that does not conform to the constraint is prevented from being entered. If a constraint is disabled, then data that does not c
onform can be allowed to enter the database.
Additionally, you can specify that existing data in the table must conform to the
constraint (VALIDATE). Conversely, if you specify NOVALIDATE, you are not ensured that existing data confo
rms.
An integrity constraint defined on a table can be in one of the following states:
ENAB
LE, VALIDATE
ENABLE, NOVALIDATE
DISABLE, VALIDATE
DISABLE, NOVALIDATE
For details about the meaning of these states and an understanding of their consequences, see the Oracle Database SQL Reference. Some of these consequences are discussed here.
To enforce the rules defined by integrity c onstraints, the constraints should always be enabled. However, consider temporarily disabling the integrity constraints of a table fo r the following performance reasons:
When loading large amounts of data into a table
When performing batch operations that make massive changes to a table (for example, changing every employee's number by add ing 1000 to the existing number)
When importing or exporting one table at a time
In all three cases, temporarily disabling integrity constraints can improve the performance of the operation, especially in data warehouse configurations.
It is possible to enter data that violates a constraint while that constraint is disabled. Thus, you should al ways enable the constraint after completing any of the operations listed in the preceding bullet list.
When a constraint is in the enable novalidate state, all subsequent statem ents are checked for conformity to the constraint. However, any existing data in the table is not checked. A table with enable novali dated constraints can contain invalid data, but it is not possible to add new invalid data to it. Enabling constraints in the novalid ated state is most useful in data warehouse configurations that are uploading valid OLTP data.
Enabling a constraint does not require validation. Enabling a constraint novalidate is much faster than enabling and validating a constraint. Also, validating a con straint that is already enabled does not require any DML locks during validation (unlike validating a previously disabled constraint) . Enforcement guarantees that no violations are introduced during the validation. Hence, enabling without validating enables you to r educe the downtime typically associated with enabling a constraint.
Using integrity constraint states in the following order can ensure the best benefits:
Disable state.
Perform the operation (load, export, import).< /p>
Enable novalidate state.
Enable state.
Some benefits of using constraints in this order are:
No locks are held.
All constraints can go to enable state concur rently.
Constraint enabling is done in parallel.
Concurrent activity on tab le is permitted.
When an integrity constraint is defined in a
CREATE TABLE or ALTER TABLE statement, it can be enabled, disabled, or validated or not validated as deter
mined by your specification of the ENABLE/DISABLE clause. If the ENABLE/DISABLE c
lause is not specified in a constraint definition, the database automatically enables and validates the constraint.
The following CREATE TABLE and ALTER TABLE
statements both define and disable integrity constraints:
CREATE TABLE emp (
empno NUMBER(5
) PRIMARY KEY DISABLE, . . . ;
ALTER TABLE emp
ADD PRIMARY KEY (empno) DISABLE;
An ALTER TABLE stateme
nt that defines and disables an integrity constraint never fails because of rows in the table that violate the integrity constraint.
The definition of the constraint is allowed because its rule is not enforced.
The following CREATE TABLE and ALTER TABLE st
atements both define and enable integrity constraints:
CREATE TABLE emp (
empno NUMBER(5) CONSTRAIN
T emp.pk PRIMARY KEY, . . . ;
ALTER TABLE emp
ADD CONSTRAINT emp.pk PRIMARY KEY (empno);
An ALTER TABLE statement that defines and attempts to enable an integrity constraint can fail because rows of the table violate the integrity con
straint. If this case, the statement is rolled back and the constraint definition is not stored and not enabled.
When you enab
le a UNIQUE or PRIMARY KEY constraint an associated index is created.
|
Note: An efficient procedure for enabling a constraint that ca n make use of parallelism is described in "Efficient Use of Integrity Constraints: A Procedure". |
The ALTER
TABLE ... RENAME CONSTRAINT statement enables you to rename any currently existing constraint for a table. The new constraint
name must not conflict with any existing constraint names for a user.
The following statement renames the dname_ukey constraint for table dept:
ALTER TABLE dept
RENAME CONSTRAINT dname_ukey TO dname
_unikey;
When you rename a constraint, all dependencies on the base table remain valid.
The RENAME CONSTRAIN
T clause provides a means of renaming system generated constraint names.
You c
an drop an integrity constraint if the rule that it enforces is no longer true, or if the constraint is no longer needed. You can dro
p the constraint using the ALTER TABLE statement with one of the following clauses:
D
ROP PRIMARY KEY
DROP UNIQUE
DROP CONSTRAINT
The following two statements drop integrity constraints. The s
econd statement keeps the index associated with the PRIMARY KEY constraint:
ALTER TABLE de
pt
DROP UNIQUE (dname, loc);
ALTER TABLE emp
DROP PRIMARY KEY KEEP INDEX,
DROP CONSTRAINT dept_fkey;
If UNIQUE or PRIMARY KEY, you must include the CASCADE CONSTRAINTS clause in the DROP statement, or you cannot drop the constraint.
When the database checks a constraint, it signal s an error if the constraint is not satisfied. You can defer checking the validity of constraints until the end of a transaction.
When you issue the SET CONSTRAINTS statement, the SET CONSTRAINTS mode lasts for the duration of the tr
ansaction, or until another SET CONSTRAINTS statement resets the mode.
|
Notes:
|
Within the applicat ion being used to manipulate the data, you must set all constraints deferred before you actually begin processing any data. Use the f ollowing DML statement to set all deferrable constraints deferred:
SET CONSTRAINTS ALL DEFERRED;
|
Note: TheSET CONSTR
AINTS statement applies only to the current transaction. The defaults specified when you create a constraint remain as long as
the constraint exists. The ALTER SESSION SET CONSTRAINTS statement applies for the current session only. |
You can che
ck for constraint violations before committing by issuing the SET CONSTRAINTS ALL IMMEDIATE statement just before issuin
g the COMMIT. If there are any problems with a constraint, this statement fails and the constraint causing the error is
identified. If you commit while constraints are violated, the transaction is rolled back and you receive an error message.
If exceptions exist when a constraint is validated, an error is returned and the integrity constraint remains novalidated. When a statement is not successfully executed because integrity constraint exceptions exist, the statement is rolled back. If exceptions exist, you cannot v alidate the constraint until all exceptions to the constraint are either updated or deleted.
To determine which rows violate t
he integrity constraint, issue the ALTER TABLE statement with the EXCEPTIONS option in the ENABLE clause. The EXCEPTIONS option places the rowid, table owner, table name, and constraint name of all exception rows i
nto a specified table.
You must create an appropriate exceptions report table to accept information from the EXCEPTIONS<
/code> option of the script or the ENABLE clause before enabling the constraint. You can create an exception table by executing the UTLEXPT1.SQL script.
Note:
Your choice of script to execute for creating theEXCEPTIONS table
is dependent upon the compatibility level of your database and the type of table you are analyzing. See the Oracle Database SQL Reference for more information.Both of these scripts create a table named EXCEPTIONS. You can create additional exceptions tables with different names by modifying and resubmitting the script.
The following
statement attempts to validate the PRIMARY KEY of the dept table, and if exceptions exist, information is
inserted into a table named EXCEPTIONS:
ALTER TABLE dept ENABLE PRIMARY KEY EXCEPTIONS INT O EXCEPTIONS;
If duplicate primary key values exist in the dept table and the name of the PRIMARY KEY<
/code> constraint on dept is sys_c00610, then the following query will display those exceptions:
SELECT * FROM EXCEPTIONS;
The following exceptions are shown:
fROWID
OWNER TABLE_NAME CONSTRAINT
------------------ --------- -------------- -----------
AAAAZ9AABAAABvqAAB SCOT
T DEPT SYS_C00610
AAAAZ9AABAAABvqAAG SCOTT DEPT SYS_C00610
A more informative query wo uld be to join the rows in an exception report table and the master table to list the actual rows that violate a specific constraint, as shown in the following statement and results:
SELECT deptno, dname, loc FROM dept, EXCEPTIONS
W
HERE EXCEPTIONS.constraint = 'SYS_C00610'
AND dept.rowid = EXCEPTIONS.row_id;
DEPTNO DNAME LOC
---------- ------
-------- -----------
10 ACCOUNTING NEW YORK
10 RESEARCH DALLAS
All rows that violate a constraint must be either updated or deleted from the table containing the constraint. When updating exceptions, you must change the value violating the constraint to a value consistent with the constraint or to a null. After the row in the master table is updated or deleted, the corresponding rows for the exception in the exception report table should be deleted to avoid confusion with later ex ception reports. The statements that update the master table and the exception report table should be in the same transaction to ensu re transaction consistency.
To correct the exceptions in the previous examples, you might issue the following transaction:
UPDATE dept SET deptno = 20 WHERE dname = 'RESEARCH'; DELETE FROM EXCEPTIONS WHERE constraint = 'SYS_C0061 0'; COMMIT;
When managing exceptions, the goal is to eliminate all exceptions in your exception report table.
|
Note: While you are correcting curre nt exceptions for a table with the constraint disabled, it is possible for other users to issue statements creating new exceptions. Y ou can avoid this by marking the constraintENABLE NOVALIDATE before you start eliminating exceptions. |
Oracle Database provides the following views that enable you to see constraint definitions on tables and to identify columns that are specified in constraints:
| View | Description |
|---|---|
DBA_CONSTRAINTS
|
DBA view describes all constraint definitions in the database. ALL view describes constraint definitions accessible to current user. |
DBA_CONS_COLUMN
S
|
DBA view describes all columns in the database that are specified in constraints. ALL view describes only
those columns accessible to current user that are specified in constraints. USER view describes only those columns owne
d by the current user that are specified in constraints. |
To rename an object, i t must be in your schema. You can rename schema objects in either of the following ways:
Drop and re-cre ate the object
Rename the object using the RENAME statement
If you drop an d re-create an object, all privileges granted for that object are lost. Privileges must be regranted when the object is re-created. p>
Alternatively, a table, view, sequence, or a private synonym of a table, view, or sequence can be renamed using the RENAM
E statement. When using the RENAME statement, integrity constraints, indexes, and grants made for the object are
carried forward for the new name. For example, the following statement renames the sales_staff view:
RENAME sales_staff TO dept_30;
|
Note: You cannot useRENAME for a stored PL/SQL program
unit, public synonym, index, or cluster. To rename such an object, you must drop and re-create it. |
Before renaming a schema object, consider the following effects:
All views and PL/SQL program units dependent on a renamed object become invalid, and must be recompiled before next use.
All synonyms for a renamed object return an error when used.
This section describes the various object dependencies, and contains the following topics:
First, review Table 20-1, which shows how objects are affected by changes to other objects on which they depend.
Table 20-1 Operations that Affect Object Status
| Operation | Resulting Status of Object | Resulting Status of Dep endent Objects |
|---|---|---|
CREATE [TABLE|SEQUENCE|SYNONYM] |
VALID i
f there are no errors |
No change1 |
ALTER TABLE (ADD, RENAME, MODIFY columns)
|
VALID if there no errors |
INVALID |
DROP [TABLE|SEQUENCE|SYNONYM|VIEW| PROCEDURE|F
UNCTION|PACKAGE] |
None. The object is dropped. | INVALID |
<
code>CREATE [VIEW|PROCEDURE]2 |
VALID if
there are no errors; INVALID if there are syntax or authorization errors |
No change1 |
CREATE OR R
EPLACE [VIEW|PROCEDURE]2 |
VALID if there
are no errors; INVALID if there are syntax or authorization errors |
|
REVOKE object privilege3 ON object TO|FROM user |
No change | All objects of
user that depend on object are INVALID3 |
REVOKE object privilege3 ON object<
/em> TO|FROM PUBLIC |
No change | All objects in the database that depend on object are INVALID3 |
REVOKE system privilege4<
/sup> TO|FROM user |
No change | All objects of user are INVALID4 |
REVOKE system privilege4 TO|FROM P
UBLIC |
No change | All obje
cts in the database are INVALID4 |
Can cause dependent objects to be made INVALID, if object did not exist earlier.
Stand alone procedures and functions, packages, and triggers.
Only DML object privileges, including SELECT, INSERT,
UPDATE, DELETE, and EXECUTE; revalidation does not require recompiling.
Only DML system privileg
es, including SELECT, INSERT, UPDATE, DELETE ANY TABLE, and EXECUTE ANY PROCEDURE; revalidation does not re
quire recompiling.
The database automatically recompiles an invalid view or PL/SQL program unit the next time it is
used. In addition, a user can force the database to recompile a view or program unit using the appropriate SQL statement with the USER/ALL/DBA_OBJECTS.
To recompile a view
manually, you must have the ALTER ANY TABLE system privilege or the view must be contained in your schema. Use the ALTER VIEW statement with the COMPILE clause to recompile a view. The following statement recompiles the view
ALTER VIEW emp_d ept COMPILE;
|
See Also: Oracle Database SQL Referenc e for syntax and other information about theALTER VIEW statement |
To recompile a standalone proced
ure manually, you must have the ALTER ANY PROCEDURE system privilege or the procedure must be contained in your schema.
Use the ALTER PROCEDURE/FUNCTION statement with the COMPILE clause to recompile a standalone procedure or f
unction. The following statement recompiles the stored procedure update_salary contained in your schema:
ALTER PROCEDURE update_salary COMPILE;
|
See Also: Oracle Database SQL Reference for syntax and other information about theA
LTER PROCEDURE statement |
To recompile a package manually, you must have the ALTER ANY PROCEDURE system privilege or
the package must be contained in your schema. Use the ALTER PACKAGE statement with the COMPILE clause to re
compile either a package body or both a package specification and body. The following statement recompiles just the body of the packa
ge acct_mgmt:
ALTER PACKAGE acct_mgmt COMPILE BODY;
The next statement compile
s both the body and specification of the package acct_mgmt:
ALTER PACKAGE acct_mgmt COMPILE PACKAGE;
|
See Also: Oracle Database SQL Reference for syntax and other information about theALTER PACKAGE statement |
Object names referenced in SQL statements can consist of several pieces, separated by periods. The followin g describes how the database resolves an object name.
Oracle Database attempts to qualify the fir
st piece of the name referenced in the SQL statement. For example, in scott.emp, scott is the first piece.
If there is only one piece, the one piece is considered the first piece.
In the current schema, the database searches for an object whose name matches the first piece of the object name. If it does not find such an object, it continues with step b.
The da tabase searches for a public synonym that matches the first piece of the name. If it does not find one, it continues with step c.
The database searches for a schema whose name matches the first piece of the object name. If it finds one, it returns to step b, now using the second piece of the nam e as the object to find in the qualified schema. If the second piece does not correspond to an object in the previously qualified sch ema or there is not a second piece, the database returns an error.
If no schema is found in step c, the object cannot be qualified and the database returns an error.
A schema object has been qualified. Any re
maining pieces of the name must match a valid part of the found object. For example, if scott.emp.deptno is the name, emp is qualified as a table, and deptno must correspond to a col
umn (because emp is a table). If emp is qualified as a package, deptno must correspond to a pu
blic constant, variable, procedure, or function of that package.
When global object names are used in a distributed database, either explicitly or indirectly within a synonym, the local database resolves the reference locally. For example, it resolv es a synonym to global object name of a remote table. The partially resolved statement is shipped to the remote database, and the rem ote database completes the resolution of the object as described here.
Because of how the database resolves references, it is possible for an object to depend on the nonexistence of other objects. This situation occurs when the dependent object uses a referen ce that would be interpreted differently were another object present. For example, assume the following:
At the current point in time, the company schema contains a table named emp.
A PUBLIC synonym named emp is created for company.emp and the SELECT privilege fo
r company.emp is granted to the PUBLIC role.
The jward schema doe
s not contain a table or private synonym named emp.
The user jward creates a v
iew in his schema with the following statement:
CREATE VIEW dept_salaries AS
SELECT deptno, MIN(s
al), AVG(sal), MAX(sal) FROM emp
GROUP BY deptno
ORDER BY deptno;
When jward creates
the dept_salaries view, the reference to emp is resolved by first looking for jward.emp as a t
able, view, or private synonym, none of which is found, and then as a public synonym named emp, which is found. As a res
ult, the database notes that jward.dept_salaries depends on the nonexistence of jward.emp and on the existe
nce of public.emp.
Now assume that jward decides to create a new view named emp in his
schema using the following statement:
CREATE VIEW emp AS
SELECT empno, ename, mgr, deptno
F
ROM company.emp;
Notice that jward.emp does not have the same structure as company.emp.
As it attempts to resolve references in object definitions, the database internally makes note of dependencies that the new dependen t object has on "nonexistent" objects--schema objects that, if they existed, would change the interpretation of the object's definiti on. Such dependencies must be noted in case a nonexistent object is later created. If a nonexistent object is created, all dependent objects must be invalidated so that dependent objects can be recompiled and verified and all dependent function-based indexes must be marked unusable.
Therefore, in the previous example, as jward.emp is created, jward.dept_salaries i
s invalidated because it depends on jward.emp. Then when jward.dept_salaries is used, the database attempts
to recompile the view. As the database resolves the reference to emp, it finds jward.emp (public.emp
is no longer the referenced object). Because jward.emp does not have a sal column, the database fin
ds errors when replacing the view, leaving it invalid.
In summary, you must manage dependencies on nonexistent objects checked during object resolution in case the nonexistent object is later created.
|
See Also: "Schema Objects and Database Lin ks" for information about name resolution in a distributed database |
The following statement sets the schema of the current session to the schema name specified in the stat ement.
ALTER SESSION SET CURRENT_SCHEMA = <schema name>
In subsequent SQL st
atements, Oracle Database uses this schema name as the schema qualifier when the qualifier is omitted. In addition, the database uses
the temporary tablespace of the specified schema for sorts, joins, and storage of temporary database objects. The session retains it
s original privileges and does not acquire any extra privileges by the preceding ALTER SESSION statement.
p>
For example:
CONNECT scott/tiger ALTER SESSION SET CURRENT_SCHEMA = joe; SELECT * FROM emp_tab;
Since emp_tab is not schema-qualified, the table name is resolved under schema joe. But if scott does not have select privilege on table joe.emp_tab, then scott cannot execute t
he SELECT statement.
Oracle Database provides a P L/SQL package that enables you to determine the DDL that created an object and data dictionary views that you can use to display info rmation about schema objects. Packages and views that are unique to specific types of schema objects are described in the associated chapters. This section describes views and packages that are generic in nature and apply to multiple schema objects.
The Oracle-supplied PL/SQL package DBMS_METADATA.GET_DDL lets you obtain metadata (in the form of DDL used to cr
eate the object) about a schema object.
The DBMS_METADATA package is a powerful tool for obtaining the complete definition of a schema object. It enables you to obtain all of the attribut
es of an object in one pass. The object is described as DDL that can be used to (re)create it.
In the following statements the
GET_DDL function is used to fetch the DDL for all tables in the current schema, filtering out nested tables and overflo
w segments. The SET_TRANSFORM_PARAM (with the handle value equal to DBMS_METADATA.SESSION_TRANSFORM meaning
"for the current session") is used to specify that storage clauses are not to be returned in the SQL DDL. Afterwards, the session-le
vel transform parameters are reset to their defaults. Once set, transform parameter values remain in effect until specifically reset
to their defaults.
EXECUTE DBMS_METADATA.SET_TRANSFORM_PARAM(
DBMS_METADATA.SESSION_TRANSFORM,'STO
RAGE',false);
SELECT DBMS_METADATA.GET_DDL('TABLE',u.table_name)
FROM USER_ALL_TABLES u
WHERE u.nested='NO'
AND (u.io
t_type is null or u.iot_type='IOT');
EXECUTE DBMS_METADATA.SET_TRANSFORM_PARAM(
DBMS_METADATA.SESSION_TRANSFORM,'DEFAULT');
The output from DBMS_METADATA.GET_DDL is a LONG datatype. When using SQL*Plus, your output may be t
runcated by default. Issue the following SQL*Plus command before issuing the DBMS_METADATA.GET_DDL statement to ensure t
hat your output is not truncated:
SQL> SET LONG 9999
See Also:
Oracle XML Developer's Kit Programmer's Guide for detailed information and further examples relating to the
use of the DBMS_METADATA package
These views display general information about schem a objects:
| View | |
|---|---|
DBA_OBJECTS
|
DBA view describes all schema objects in the database. ALL view describes objects accessible to
current user. USER view describes objects owned by the current user. |
DBA_CATALOG
| List the name, type, and owner (USER view does not display owner) for a
ll tables, views, synonyms, and sequences in the database. |
DBA_DEPENDENCIES
|
Describe all dependencies between procedures, packages, functions, package bodies, and trigge rs, including dependencies on views without any database links. |
The following sections contain examples of using some of these views.
|
See Also: Oracle Database Reference for a complete description of data dictionary views |
The f ollowing query lists all of the objects owned by the user issuing the query:
SELECT OBJECT_NAME, OBJECT
_TYPE
FROM USER_OBJECTS;
The following is the query output:
OBJECT_NAME
OBJECT_TYPE
------------------------- -------------------
EMP_DEPT CLUSTER
EMP TABLE
DEPT
TABLE
EMP_DEPT_INDEX INDEX
PUBLIC_EMP SYNONYM
EMP_MGR VIEW
<
/a>When you create a view or a synonym, the view or
synonym is based on its underlying base object. The ALL_DEPENDENCIES, USER_DEPENDENCIES, and
DBA_DEPENDENCIES data dictionary views can be used to reveal the dependencies for a view. The ALL_SYN
ONYMS, USER_SYNONYMS, and DBA_SYNONYMS data dictionary views can be used to list the base object of
a synonym. For example, the following query lists the base objects for the synonyms created by user jward:
SELECT TABLE_OWNER, TABLE_NAME, SYNONYM_NAME
FROM DBA_SYNONYMS
WHERE OWNER = 'JWARD';
The follow ing is the query output:
TABLE_OWNER TABLE_NAME SYNONYM_NAME ---------------------- ---- ------- ----------------- SCOTT DEPT DEPT SCOTT EMP EMP