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

Oracle XSQL- P10 potx

20 256 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

Định dạng
Số trang 20
Dung lượng 237,65 KB

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

Nội dung

Of course, to do this from XSQL requires that you perform the following: SELECT sysdate AS “Date” FROM dual You can also use the dual table to include parameters in the result set:

Trang 1

Table 8.15 Set Comparison Operators

belongs to the specified set WHERE sal IN

(800,950,1100) NOT IN Tests if an operand doesn't SELECT ename FROM emp

belong to the specified set WHERE sal NOT IN

(800,950,1100) ANY Used in conjunction with SELECT ename FROM emp

a relationship comparison WHERE sal > ANY operator Determines if the (800,950,1100) specified relationship is

true for any of the values

SOME Used in conjunction with SELECT ename FROM emp

a relationship comparison WHERE sal > SOME operator Determines if the (800,950,1100) specified relationship is true

for one or more of the values

ALL Used in conjunction with SELECT ename FROM emp

a relationship comparison WHERE sal > ALL operator Determines if the (800,950,1100) specified relationship is true

for all of the values

The Imaginary Dual Table

Oracle provides the dual table, an imaginary table used largely for allowing you to

per-form functions For instance, if you want to use a select statement to get the current date, you could do so as follows:

SELECT sysdate FROM dual

Table 8.16 Set Operators

UNION All unique rows of both queries are returned

UNION ALL All rows of both queries are returned

MINUS Eliminates rows that appear in the second query from the

rows returned in the first query

INTERSECT Returns only the rows that are common to both queries

Trang 2

Of course, to do this from XSQL requires that you perform the following:

<?xml version=”1.0”?>

<page connection=”demo” xmlns:xsql=”urn:oracle-xsql”>

<xsql:query>

SELECT sysdate AS “Date” FROM dual

</xsql:query>

</page>

You can also use the dual table to include parameters in the result set:

<?xml version=”1.0”?>

<page connection=”demo” xmlns:xsql=”urn:oracle-xsql”>

<xsql:query>

select ‘{@param}’ AS “ParamName” FROM dual

</xsql:query>

</page>

Managing Tables

The select statement is the tool used for getting data out of the database The flip side of select is getting data in to the database Before you can do that, however, you must have places to put the data The construction of the database is the job of Data Definition Language (DDL) statements, which create, modify, or delete objects in the Oracle database This section covers the part of DDL that pertains to the most popular and useful type of object, tables

There are a lot of things to consider when managing your table At the highest level, you must decide what data you want in the table You think about this based on how you want this table to fit in to the rest of your application But there are lots of system level attributes to consider, also Ultimately, you’ll want to work with your DBA on a lot of these parameters Here, you’ll get a gentle introduction

Creating Tables

There are many options in creating tables In this section, first you’ll examine the sim-plest way to create a table; then you’ll examine some of the more useful aspects of table creation A lot of the options presented here concern how the table is stored Finally, you’ll learn how to create an exact copy of another table The following SQL will create

a table for customer orders You’ll use this table in later examples, so you should create

it under the momnpop id

CREATE TABLE customer (

custid NUMBER(8),

fname VARCHAR2(30),

lname VARCHAR2(30),

address1 VARCHAR2(50),

Trang 3

address2 VARCHAR2(50),

state VARCHAR(5),

zip VARCHAR(10),

country VARCHAR(5)

);

If you now do a desc customer, you’ll see that your table is in place There are, however, a few problems that you will run into immediately First, the custid will be used to identify your customers uniquely You don’t want someone using the same cus-tomer identification (id) twice There is an easy way to prevent this from happening— just issue the following command:

T I P To get rid of the old table, just issue the command DROP TABLE

customer;

CREATE TABLE customer (

custid NUMBER(4) PRIMARY KEY,

fname VARCHAR2(30),

lname VARCHAR2(30),

address1 VARCHAR2(50),

address2 VARCHAR2(50),

state VARCHAR(5),

zip VARCHAR(10),

country VARCHAR(5)

);

The database will now automatically prevent anyone from reusing the same custid Your next problem concerns the country column Because most of your cus-tomers are in the United States, you will want to set USA as the default value If the value of the country column isn’t explicitly defined in an insert statement, it will be USA The first sentence asks that you set USA as the default value; the second sentence (as well as first sentence following the display code below) says that if you don’t explicitly define (set?) the default value, it will be USA You can define the default value with the following code:

CREATE TABLE customer (

custid NUMBER(4) PRIMARY KEY,

fname VARCHAR2(30),

lname VARCHAR2(30),

email VARCHAR2(30),

address1 VARCHAR2(50),

address2 VARCHAR2(50),

state VARCHAR(5),

zip VARCHAR(10),

country VARCHAR(5) DEFAULT ‘USA’

);

Trang 4

Now, one thing you do want your user to define is his or her last name If you don’t define the last name, the row will be completely useless You can require that the last name be defined as follows:

CREATE TABLE customer (

custid NUMBER(4) PRIMARY KEY,

fname VARCHAR2(30),

lname VARCHAR2(30) NOT NULL,

email VARCHAR2(30),

address1 VARCHAR2(50),

address2 VARCHAR2(50),

state VARCHAR(5),

zip VARCHAR(10),

country VARCHAR(5) DEFAULT ‘USA’

);

N OT E The NOT NULL and PRIMARY KEY are examples of constraints, which

you will learn more about later in the chapter The best time to create them is

along with the table, so a couple are introduced here You’ll see all of them in a

little while.

Your next problem is that you want the table to live on a particular tablespace You expect to get a lot of customers, so you want this table to be on your new terabyte drive Here’s how you would do that, assuming the tablespace is named cust_tablespace:

CREATE TABLE customer (

custid NUMBER(4) PRIMARY KEY,

fname VARCHAR2(30),

lname VARCHAR2(30) NOT NULL,

email VARCHAR2(30),

address1 VARCHAR2(50),

address2 VARCHAR2(50),

state VARCHAR(5),

zip VARCHAR(10),

country VARCHAR(5) DEFAULT ‘USA’

)

TABLESPACE cust_tablespace;

N OT E There are many other storage options for your table that allow you to

fine-tune how your data is stored They require a deep understanding of the

Oracle architecture to be used properly These options are beyond the scope of

this text and aren’t covered here.

Trang 5

Let’s say that you want to base your table on data that already exists in the system.

By using the AS keyword, you can create a new table based on the following select statement, and the table will automatically populate Notice that you use the aliasing you learned earlier to change the empno column name to EMPID

CREATE TABLE empdept

AS SELECT empnoAS”EMPID”,ename,dname

FROM emp,dept WHERE emp.deptno=dept.deptno;

The last topic for this section concerns temporary tables, used for storing data on a

per-session basis The data you put in can be seen only by your session, at the end of which the data goes away Other sessions can use the same temporary table at the same time and your session won’t see their data Temporary tables are often used in complex queries for which you need to grab a subset of data They have limited usefulness in conjunction with XSQL pages because of the short duration of an XSQL session How-ever, there may be some situations in which you’ll find it much easier and efficient to process a subset from a temporary table rather than to repeatedly requery the database

or load the data set into memory Here is how a temporary table is created:

CREATE GLOBAL TEMPORARY TABLE temptable (

temp_col1 VARCHAR2(20),

temp_col2 VARCHAR2(20)

);

Altering Tables

The alter table statement allows you to change aspects in a table that has already been created In many cases, you can make changes to a table that already has data in

it This section looks at how the alter table statement works, what it is usually used for, and what it can’t be used for Before beginning the discussion, it’s important to note that you can modify the storage characteristics of tables These characteristics won’t be itemized here, but most can be altered at any time In this section, most of the empha-sis is on working with columns, but it also covers moving a table to a new tablespace Some discussion of constraints is given, but the “Constraints” section provides the greatest discussion of that topic

Working with Columns

The alter table statement works almost exactly like the create table statement;

it shares most of the same keywords and syntax However, to use the alter table statement with columns is troublesome when you work with existing columns that are already populated with data It is far simpler to add a column to a table Here’s an example that uses the emp table you created previously It adds to the table a home_phonecolumn

Trang 6

ALTER TABLE emp ADD

(home_phone VARCHAR2(10));

The good news is that adding a basic column is easy It’s even easy to add a column that has a default value, as follows:

ALTER TABLE emp ADD

(benefits VARCHAR2(20) DEFAULT ‘STANDARD HEALTH’);

But if your table already has data in it, things get more complex For instance, what

if you want to create a column as NOT NULL? Each row has to have a value As shown

in the following, the syntax is simple enough:

ALTER TABLE emp ADD

(home_zip VARCHAR2(10) NOT NULL);

If you run this against the emp table, which has data in it, you will get the following error message:

ORA-01758: table must be empty to add mandatory (NOT NULL) column

The problem is that at the time you add the column, all the data is null The NOT NULL constraint couldn’t possibly be satisfied You have several alternatives:

■■ Set a default value for the column, such as ALTER TABLE emp ADD

(home_zip VARCHAR2(10) NOT NULL DEFAULT ‘27607’);

■■ Remove all the data and alter the column

■■ Create the column without the NOT NULL constraint, add the data, and apply

the NOT NULL constraint afterwards

The second option leads directly to the discussion about altering existing columns

To make these alterations, you would use the modify keyword and a similar expres-sion that you would use if you were creating the column from scratch

ALTER TABLE emp ADD (

home_zip VARCHAR2(10));

add the data home zip data

ALTER TABLE emp MODIFY (

home_zip NOT NULL);

You don’t need to include anything about the data type, since that would remain the same However, if you want to change the data type, you can But there are restrictions Anything goes if the column has no data in it If you want, you can even change the data type entirely from varchar2 to date, date to number, number to varchar2, and so

on If, however, there is any data in the column, this kind of modification isn’t allowed Table 8.17 lists the rules for modifying columns that already contain data

Trang 7

Table 8.17 Modifying Columns Containing Data

Assigning Using the DEFAULT Always ALTER TABLE emp default value keyword to specify a MODIFY (home_zip

default value for the DEFAULT 27609) column The default

value will only be used moving forward;

null and other values already in the system will remain the same

Widening strings Increasing the number Always ALTER TABLE emp

of characters allowed MODIFY (home_zip

VARCHAR2(12)) Narrowing strings Decreasing the Only to ALTER TABLE emp

number of characters longest MODIFY (ename allowed Oracle won't string VARCHAR2(7));

do this if it would length require any existing

string to be shortened

Increasing scale Increasing the number Always ALTER TABLE emp For numbers of digits to the left MODIFY (empno

of the decimal point NUMBER(6,0)) Increasing Increasing the number Always ALTER TABLE emp precision For of digits to the right MODIFY (empno

Decreasing scale Shrinking the size of No

and precision a number column on

For numbers either the left or

right of the column

Our last topic for this section concerns dropping a column altogether, the ultimate modification This can be accomplished by way of the drop column clause If there is data in the column, it will be deleted

alter table emp drop column home_zip;

Dropping Tables

Dropping tables is the process of removing a table and all of its data from your data-base To drop a table, you need the drop table privilege for the table Also, you need

to be very careful; if you are having a bad day, you might end up inadvertently drop-ping the incorrect table

Trang 8

There are two ways to drop tables The following way you’ve already seen:

DROP TABLE table_to_drop;

Often when trying to drop a table, you will encounter the following error message:

ORA-02449: unique/primary keys in table referenced by foreign keys

You get this error message because foreign key constraints are being used You learn more about foreign key constraints later; for now, it’s important to know only that there are rows in other tables that reference keys in this table If you just go and drop this table, those other tables will be very, very upset Thus, Oracle doesn’t allow you to

do it Here are ways around this problem:

■■ Getting rid of the foreign key constraints; then dropping the table

■■ Deleting the data that references this table

■■ Dropping this table and all the tables with references to it

The first two options will be examined in the foreign constraints discussion The last option is a bit draconian and risky: You delete the table_to_drop table and recur-sively drop all tables that have a reference to it Oracle will drop the tables with refer-ences to your target table, and if it finds that it can’t drop a table because another table has a reference to it, it will go and find that table and then drop that one too It’s like a scorched-earth campaign against the ORA-02449 error Use with care

DROP TABLE table_to_drop CASCADE CONSTRAINTS;

Adding and Modifying Data

Now that you’ve created some tables, you are ready to put data in them Data is added

to tables by way of the insert statement, existing data is changed by way of the updatestatement, and data is removed by way of the delete statement The cus-tomer table created earlier for examples is used for discussing all these statements Before these statements are discussed, sequences are introduced Sequences solve a fundamental problem—that of creating unique keys for your tables But before you read about any of these topics, you need to learn about Oracle transactions

When you add and modify data, you use the xsql:dml action This action isn’t lim-ited to only one SQL statement the way that the xsql:select action is Even though our examples here use one statement only, you can combine as many statements as you like between the begin and end statements inside the xsql:dml element

Transactions

A transaction is one or more SQL statements executing against the database They are very important when you work with Data Manipulation Language (DML) statements because you often want all of the statements to succeed or fail as a group A classic

Trang 9

example is a banking transaction in which $100 is transferred from a savings to a checking account This transaction really involves three steps:

1 Subtract $100 from savings

2 Add $100 to checking

3 Record the transaction in the transaction log

If any of the preceding statements fail individually, you will have problems If the cus-tomer doesn’t have $100 in savings, you will hand him or her free money to put into their checking account If a problem occurs in adding the money to checking, you will have an upset customer If you can’t log the transaction, you will have bookkeeping problems in the future

Oracle addresses this problem with the commit, rollback, and savepoint state-ments No data is saved permanently to the database until a commit is issued The commitis the end of the transaction, and the first SQL statement issued—either in a session or after a commit—is the beginning of the session

If you run into trouble halfway through a transaction, you can issue a rollback to tell Oracle to ignore all the statements that have been executed so far in the transaction The database is rolled back to the state that it was in before the start of the transaction You can also specify a savepoint, which is an intermediate commit At the time you issue a savepoint, no data is permanently written to the database; instead, you have a point to roll back to other than the beginning of the transaction This can save time and horsepower, because you don’t have to repeat all of the work that was done before you issue the savepoint, which is presumably okay

Sequences

Earlier, you created a table with a primary key The purpose of the primary key is to uniquely identify each row in your table Each time you insert a new row, you need to create a new, unique key You know that Oracle won’t let you insert a nonunique key, but how do you generate a new key? Finding the last key used is one strategy, but what

if multiple sessions are creating new keys at the same time?

Fortunately, there is an easy solution—a sequence An Oracle sequence generates a sequence of numbers The numbers are guaranteed to be unique Each time a call is made, the next number in the sequence is returned Here is a simple sequence:

create sequence my_seq;

To use the sequence to generate ids, you can use the dual table as follows:

<?xml version=”1.0”?>

<page connection=”demo” xmlns:xsql=”urn:oracle-xsql”>

<xsql:query>

Trang 10

SELECT my_seq.nextval FROM dual

</xsql:query>

</page>

If you are interested in getting the last value that was selected—known as the current value—you can do that as follows:

SELECT my_seq.currval FROM dual

Each time you reload the page, you will get a new sequence number By default, a sequence starts at 1, increments by 1, has no max value (other than 10^27), will never cycle back to where it started, will cache 20 numbers at a time, and does not guarantee that numbers will be generated in the order of the request All these options can be tweaked, as listed in Table 8.18

Table 8.18 Sequence Options

INCREMENT BY Value to increment by create sequence

between calls Can be negative my_seq increment by 2 START WITH The first sequence number to create sequence

be generated Defaults to my_seq start with 10 MINVALUEfor ascending

sequences and MAXVALUE for descending sequences

MAXVALUE The largest value possible for create sequence

the sequence Default is 10^27 my_seq MAXVALUE 9999 MINVALUE The smallest value possible create sequence

for the sequence Default is 1 my_seq MINVALUE 20 CYCLE The sequence will cycle when create sequence

either MINVALUE or MAXVALUE my_seq CYCLE

is reached

CACHE Number of numbers that will Create sequence

be kept in cache Unused my_seq CACHE 100 numbers are lost when the

database shuts down

ORDER The sequence will guarantee CREATE SEQUENCE

that numbers are returned in my_seq ORDER the order that requests were

received

Ngày đăng: 03/07/2014, 08:20

TỪ KHÓA LIÊN QUAN

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

TÀI LIỆU LIÊN QUAN