Vous êtes sur la page 1sur 9

SQL for Views, Synonyms, and Sequences

13
C H A P T E R

In This Chapter
Using SQL for creating views Creating private and public Synonyms Setting up sequences

T
See Reference Section CrossReference

his chapter explores how to create and modify views, Synonyms, and sequences using classic SQL.

At the beginning of each section, a cross-reference points to the appropriate command in the Command Reference section of this book. Watch for the See Reference Section icon in the margin. Chapter 8 contains complete instructions for views, Synonyms, and sequences using the Schema Manager.

Views
Views have one primary purpose: to rearrange the way you see a Table, a portion of a Table, or a group of Tables without actually creating any copies of the underlying data. Views enable you to use the data in more convenient packaging. For example, a certain Table contains all valid orders for every customer. You could create a view that shows you the valid orders for a single customer and reuse this view when displaying data to your customer on your Web site.
CrossReference

Chapter 24 shows how to create views based on Objects (Object views). You can use a view anywhere you use a Table. You can use views in the FROM clause of your SQL query or even in an INSERT, UPDATE, or DELETE command.

268

Chapter 13 3 SQL for Views, Synonyms, and Sequences

Modifying data using views


When you update data using a view, you actually update the underlying Tables data. This condition also applies when you insert or delete from a view. You cannot use some kinds of views for modifying data: 3 Views with set operators such as INTERSECT, UNION, and MINUS 3 Views with GROUP BY, Connect BY, or START WITH clauses 3 Views with group functions such as AVG, SUM, or MAX 3 Views using the DISTINCT function 3 Views which join Tables (with some exceptions) You can create views that join several Tables and still allow the update of one Table. The updateable Table must have a unique Index on at least one Column in the joined Table. Even then, all Columns in the view are not updateable. To determine which Columns, if any, are updateable, query the Data Dictionary view called USER_UPDATABLE_COLUMNS. This view displays the updateable Columns. For example, if you create a view named TANK_ANIMALS_VIEW that joins two Tables, the following SQL SELECT command shows which Columns you can use for updating:
SELECT COLUMN_NAME, UPDATABLE FROM USER_UPDATABLE_COLUMNS WHERE TABLE_NAME = TANK_ANIMALS_VIEW;

You can use views to restrict the kind of data inserted or updated into the underlying Table with the WITH CHECK OPTION parameter. The WITH CHECK OPTION states all data modified through the view must fit within the view.

Creating a new view


See Reference Section

CREATE VIEW

This section describes how to create a view using the SQL CREATE VIEW command. The basic syntax of the command follows:
CREATE [OR REPLACE] [FORCE/NO FORCE] VIEW [user.]view [column_name1, column_name2] AS query [WITH OBJECT OID | DEFAULT] [WITH CHECK OPTION] [CONSTRAINT constraint] [WITH READ ONLY]

Chapter 13 3 Views

269

At a minimum, you must name and write the query for the view. If you leave out the list of Columns, Oracle8 uses the Column names in the query as the views Column names. As an example, a new view called CARETAKER_ANIMAL_VIEW is created. It merges the two Tables: TANK and AQUATIC_ANIMAL. (See Figure 7-1 in Chapter 7 for a database diagram showing the relationship of these Tables.) The query assumes the User logged in to Oracle8 is the name of the CARETAKER. The query follows:
SELECT TANK_NAME, ANIMAL_NAME, BIRTH_DATE FROM TANK T , AQUATIC_ANIMAL A WHERE CHIEF_CARETAKER_NAME = USER AND T.TANK_NO = A.TANK_NO

Other options that you can use with your view include: 3 OR REPLACE. Allows the new view to replace an existing view of the same name. 3 FORCE. Creates the view even though the creator does not have SELECT privileges on the underlying Tables. This option also creates a view that references a nonexistent Table. This type of view is invalid until the underlying Table exists and the User executing the view has appropriate privileges on the underlying Table. 3 WITH READ ONLY. Prevents all but query access to the view. 3 CONSTRAINT. Adds Constraints on the Columns in the view. Use this option for views with UPDATES and INSERTS. 3 WITH CHECK. Restricts the User to inserting and updating rows that fit within the view. (Warning: this option may not work properly if the view contains a subquery.) Use this option for views with UPDATES and INSERTS.
CrossReference

Any valid SQL query can be used in a view. The query can use Column functions, pseudocolumns, group functions, and so forth. To learn more about constructing queries, see Chapter 9. Here is an example of a view that uses a subquery. The goal is to present the User with a view of the AQUATIC_ANIMAL Table that only shows his own animals. The animals exist in tanks to which the User is assigned via the CHIEF_CARETAKER_NAME Column in the TANK Table. To simplify the example, assume the CHIEF_CARETAKER_NAME is the Oracle8 Username. The SQL for the view follows:
CREATE VIEW ANIMAL_FOR_ONE_CARETAKER_VIEW AS SELECT * FROM AQUATIC_ANIMAL A WHERE EXISTS (SELECT X FROM TANK T WHERE T.TANK_NO = A.TANK_NO AND T.CHIEF_CARETAKER_NAME = USER)

Example

270

Chapter 13 3 SQL for Views, Synonyms, and Sequences

See Reference Section

PSEUDOCOLUMN

The preceding example contains a Column called USER in the last line. Oracle8 has a small set of Columns available in every Table, even though none of the Tables definitions actually contain the Columns; these Columns are called pseudocolumns. USER is a pseudocolumn. See the Command Reference section for a complete list of pseudocolumns. Similarly, Oracle8 has a small Table called DUAL owned by the SYSTEM User ID and accessible to all Oracle Users. DUAL always has one row and one Column. (Now that I think about it, I wonder why Oracle called the Table DUAL you should call it SINGLE!) See the next section for a discussion of pseudocolumns and the proper use of the DUAL Table. The next section shows how to change a view.

Changing a view with SQL


The syntax for changing a view is identical to creating a view, except you must use the parameter for replacing the view. The syntax follows:
CREATE OR REPLACE [FORCE/NO FORCE] VIEW [user.]view [column_name1, column_name2] AS query [WITH OBJECT OID | DEFAULT] [WITH CHECK OPTION] [CONSTRAINT constraint] [WITH READ ONLY]
Tip

Save your CREATE VIEW SQL statement in a file where you can easily edit and execute the command. The following SQL query extracts the query from an existing view:
SELECT TEXT FROM USER_VIEWS WHERE VIEW_NAME = yourview

Replace yourview with the actual view name. The next section shows how to remove a view.

Deleting (dropping) a View


Deleting a view with the SQL is similar to deleting other Objects. The general syntax follows:
DROP VIEW viewname

Chapter 13 3 Synonyms

271

Replace viewname with the actual view you want to drop. You can use views for many tasks. Oracle8s Optimizer handles views as it handles any SQL query. Therefore, unlike SQL queries, you do not lose performance with views. The Synonym is another useful Object. The next section shows how to create and manage Synonyms using SQL.

Synonyms
Primarily, Synonyms enable multiple Users to reference an Object without adding the Schema as a prefix to the Object. You can make a Synonym for a Table, view, or even another Synonym. In addition, you can create Synonyms for functions, Packages, Procedures, sequences, and database links to remote databases. After creation, you can use a Synonym as though it were the underlying Object. Like views, Synonyms do not contain their own data they are only a different way of referencing the underlying data. A Synonym can be private or public. Private Synonyms are created by a User for her own use and sole access. Public Synonyms are created by the DBA and shared among all Users. Oracle8 comes with a set of public Synonyms that reference the Data Dictionary views. Data Dictionary views are convenient reference views which enable you to use SQL queries to extract Table names, Column attributes, space usage, and other important database details.
CrossReference

Table 8-1 in Chapter 8 lists some of the available Data Dictionary views. Synonyms are not the first Objects retrieved when Oracle8 looks for a match on a Table name. When an SQL command contains a Table name without the Schema prefix, Oracle8 searches for a match for the Table name using the following hierarchy: 1. Table owned by the current User. 2. Private Synonym owned by the current User. 3. Public Synonym. Some of the typical uses of Synonyms are: 3 Shortening Table names. Application developers typically use private Synonyms as shorthand for Tables they need to reference often during SQL code development. This approach avoids the retyping of long Table names.

272

Chapter 13 3 SQL for Views, Synonyms, and Sequences

3 Smoothing migration. Public Synonyms simplify the migration of applications. If the Schema names are different but the Tables are the same, an application can migrate easily from database to database. Typically, Synonyms are used to simplify the migration of applications from a development or test platform to a production platform. 3 Centralizing references. Sometimes, the DBA uses public Synonyms for common lookup Tables needed across multiple Schemas. 3 Renaming Tables. Public Synonyms also enable two User groups to refer to a single Table with two different names. Views typically perform this task, but if the underlying Table is identical and each group wants a business-rule appropriate name, a Synonym may be a good solution. For example, the accounting department may refer to the customer Table as CUSTOMER while the sales department insists the same Table must be named CLIENT. Creating two Synonyms for the same Table satisfies both departments.
Caution

When creating public Synonyms, Oracle8 Users often mistakenly assume they can immediately share their Tables with other Oracle8 Users. Creating a public Synonym for a Table does not automatically enable other Users to view or change the data in your Table. You must still assign the appropriate privileges using the Security Manager or SQL GRANT command. The next section shows how to use the Schema Manager to create a new Synonym.

Creating a new Synonym


The basic syntax for creating a Synonym follows:
CREATE [PUBLIC] SYNONYM [user.] synonym FOR [user.] table [@database_link]

For example, use the following SQL command to create a public Synonym named CREATURE for the SEAPARK.AQUATIC_ANIMAL Table in the local database:
CREATE PUBLIC SYNONYM CREATURE FOR SEAPARK.AQUATIC_ANIMAL

You cannot modify or alter Synonyms. The next section shows how to delete Synonyms.

Deleting (dropping) a Synonym


Deleting a Synonym with SQL is similar to deleting other Objects. The simple syntax follows:
DROP [PUBLIC] SYNONYM synonym

Chapter 13 3 Sequences

273

The next section shows how to create and manage sequences, which you use for assigning sequential numbers in a way that accommodates concurrent Users.

Sequences
A sequence is an Oracle8 Object that delivers a unique number, incremented by one or some specified amount, every time it is requested. Sequences are typically used to generate a Primary Key for a Table or set of Tables. The sequence generates a new number each time it is called. The number increments every time, regardless of the state of the transaction, thus guaranteeing unique numbers. For example, User A starts an application that begins building a row to insert in a Table. The application calls a sequence and retrieves the next value from the sequence, 109. User A has not committed the transaction. At the same time, User B creates a new row for the same Table. User B calls the same sequence and receives the number 110. User B commits her record. User A rolls back his transaction. User C inserts a row, calling the same sequence and receiving the number 111. User C commits the row. The Table now has two rows with Primary Keys of 110 and 111. The next time a User calls the sequence, it will send number 112 and so forth.
Tip

A sequence is not directly connected with any Table; instead, sequences simply deliver sequence numbers. Any number of Tables can share the same sequence to retrieve numbers. The Tables only become connected with the sequence indirectly through a Trigger or the use of the NEXTVAL function in the INSERT command.

Creating a new sequence


See Reference Section

CREATE SEQUENCE

A new sequence can easily be created using SQL. Like other Objects, a sequence is owned by a Schema and can be referenced with a Synonym. Only the SELECT privilege can be granted for a sequence. Granting SELECT on a sequence enables the User to retrieve sequence numbers from the sequence. The general syntax for creating a sequence follows:
CREATE SEQUENCE [user.]sequence [ INCREMENT BY n] [ START WITH n] [ MAXVALUE n | NOMAXVALUE] [ MINVALUE n | NOMINVALUE] [ CYCLE | NOCYCLE] [CACHE n | NOCACHE] [ORDER | NOORDER]

274

Chapter 13 3 SQL for Views, Synonyms, and Sequences

At a minimum, you must name the sequence. All other parameters have default values. The parameters are: 3 INCREMENT BY. The default is 1. To create a sequence that issues numbers in decreasing value, use a negative number such as -1. 3 START WITH. The default starts a sequence with 1. You can also specify a different number. 3 MINVALUE. Choose the default of NOMINVALUE if you want the descending sequence to end at -1026. 3 MAXVALUE. Choose the default of NOMINVALUE if you want the ascending sequence to end at 1026. 3 CYCLE. The default is NOCYCLE. Use CYCLE if you want the sequence to start back at the beginning when it reaches the maximum (or minimum for descending) value. Use the default (NOCYCLE) to stop the sequence when it reaches the end. 3 CACHE. By default, Oracle8 caches 20 numbers. NOCACHE instructs Oracle8 not to cache any sequence numbers. Enter a CACHE number to specify the number of sequence numbers to be cached. This number cannot exceed the number of sequence numbers spanning the life of the sequence. For example, a sequence that increments by 5, begins at 5, and ends at 50 cannot cache more than 10 numbers. 3 ORDER. The default is NOORDER. Specify the ORDER parameter to instruct Oracle8 to generate sequence numbers in the requested order when in a parallel environment. The ORDER parameter is only relevant for parallel processing: you do not need it to generate Primary Keys, but it does make a difference in parallel databases where the sequence is used as a timestamp. Once a sequence is created, you can use it to generate sequence numbers. The next section shows how to modify some parameters of the sequence.

Changing (altering) a sequence


See Reference Section

ALTER SEQUENCE

When changing a sequence, take care to not specify changes that will compromise the uniqueness of the Primary Keys depending on the sequence. The following syntax alters a sequence:
ALTER SEQUENCE [user.]sequence [ INCREMENT BY n] [ MAXVALUE n | NOMAXVALUE] [ MINVALUE n | NOMINVALUE] [ CYCLE | NO CYCLE] [CACHE n | NO CACHE] [ORDER | NO ORDER]

Chapter 13 3 Summary

275

See the preceding section for descriptions of these parameters. If you need to reset a sequence to a starting number higher than the current value of the sequence, you must drop the sequence and re-create it. The next section shows how to drop a sequence.

Deleting (dropping) a sequence


Deleting a sequence with the Schema Manager is similar to deleting other Objects. The following syntax drops a sequence:
DROP SEQUENCE [schema.]sequence

Remember: dropping a sequence causes Oracle8 to remove any privileges granted on the sequence. Synonyms remain but are invalid. Triggers using the dropped sequence remain but issue an error message when used.

Summary
Views help streamline access to data by hiding complexities of the underlying Tables. Views can also help separate data for different Users as a security measure. Views can be referenced almost anywhere you reference a Table. Views are stored in the database as an SQL SELECT command and have no data of their own. The Schema Manager is used to create views; it does not aid in the writing of the underlying query, however. Creating views using SQL Worksheet or SQL*Plus (instead of Schema Manager) is just as easy. Synonyms enable developers to reference Tables with shorthand names. Synonyms also allow different applications to reference the same Object with different names. Synonyms can help simplify migration of applications from one Schema or database instance to another. Sequences can quickly and easily assign unique numbers for Primary Keys. With sequences, you do not need to query a Table to find the highest Primary Key. In addition, sequences are safer than other application-generated methods because they handle multiple concurrent Users seamlessly. The next chapter shows how to use SQL*Plus to write a report.

Vous aimerez peut-être aussi