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

Tài liệu Manipulating data docx

54 251 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 đề Manipulating Data
Trường học Vietnam National University
Chuyên ngành Database Management
Thể loại Giáo trình đào tạo
Thành phố Hà Nội
Định dạng
Số trang 54
Dung lượng 388,34 KB

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

Nội dung

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć2Schedule: Timing Topic 45 minutes Lecture 40 minutes Practice 85 minutes Total Class Management Note: Files required fo

Trang 1

Manipulating Data

11

Trang 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć2

Schedule: Timing Topic

45 minutes Lecture

40 minutes Practice

85 minutes Total

Class Management Note:

Files required for this lesson are:

Demonstration: l11sel.sql, l11upd.sql

Practice: None

Trang 3

Manipulating Data 11Ć3

Once your tables have been created, you will need to add new rows, make

changes to rows in a table, or delete rows by using data manipulation

commands This lesson covers using SQL commands to make changes to data A number of these data manipulation commands make up a transaction, which you may either save or delete using transaction controls.

At the end of this lesson, you should be able to

D Insert new rows into a table

D Update existing rows in a table

D Delete rows from a table

D Explain transaction controls and their importance

Trang 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć4

Trang 5

Manipulating Data 11Ć5

update, or delete data in the database, you execute a DML statement A collection of

DML statements that have not yet been made permanent is called a transaction, or a

logical unit of work

Technical Note:

The only way to manipulate data within the Oracle database is by means ofthe data manipulation SQL statements listed here The statements can beissued directly in SQL*Plus or SQL*DBA, performed automatically bytools such as Developer/2000 and SQL*Loader, or programmed with toolssuch as the 3GL Precompilers There is one exception: SQL*Loader has aDirect Mode option for the Oracle7 Server that loads rows into the databasewithout using the INSERT statement

Every table has INSERT, UPDATE, and DELETE privileges associatedwith it These privileges are automatically granted to the creator of thetable, but in general they must be explicitly granted to other users

A new feature to Oracle 7.2 is that you can place a subquery in the place ofthe table name, essentially the same way a view is used For example,

UPDATE (SELECT * FROM s_dept)

SET id = 50

WHERE id = 60;

Trang 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć6

Trang 7

Manipulating Data 11Ć7

Syntax

where: table is the table name

column is the name of the column in the table to

populate

value is the corresponding value for the column

Note: This command with the VALUES clause adds only one row at a time to a

table

Inserting a Row into a Table

Because you can insert a new row that contains values for each column, therefore thecolumn list is not required in the INSERT clause However, the values must be listedaccording to the default order of the columns in the table

SQL> DESCRIBE s_dept

Name Null? Type

- -

-ID NOT NULL NUMBER(7)

NAME NOT NULL VARCHAR2(25)

REGION_ID NUMBER(7)

SQL> INSERT INTO s_dept

2 VALUES (11, ’Finance’, 2);

1 row created

For clarity, use the column list in the INSERT clause

Enclose character and date values within single quotation marks; do not enclose

numeric values within single quotation marks

Trang 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć8

Class Management Note:

Common errors that can occur during user input:

1 Mandatory value missing for a NOT NULL column

2 Duplicate value violates uniqueness constraint

3 Foreign key constraint violated

4 CHECK constraint violated

5 Datatype mismatch

6 Value too wide to fit in column

Trang 9

Manipulating Data 11Ć9

Inserting Null Values

Method Description

Implicit Omit the column from the column list

Explicit Specify the NULL keyword in the VALUES list

Specify the empty string (‘’) in the VALUES list; forcharacter strings and dates only

Example

Enter a new department omitting the region number Because the region number isnot listed in the INSERT clause, a null value is entered implicitly for the regionnumber in this row

SQL> INSERT INTO s_dept (id, name)

SQL> INSERT INTO s_dept

2 VALUES (13, ’Administration’, NULL);

Trang 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć10

Trang 11

Manipulating Data 11Ć11

Inserting Special Values by Using SQL Functions

You can use pseudocolumns to enter special values in your table Specify USERID toenter the current user name SYSDATE enters the current date and time

Example

Record information for the student in the S_EMP table Supply the current user namefor the USERID column and the current date and time in the START_DATE column

SQL> INSERT INTO s_emp (id, first_name,

2 last_name, userid, salary, start_date)

3 VALUES (26, ’Donna’,

4 ’Smith’, USER, NULL, SYSDATE);

1 row created

Confirming Additions to the Table

To verify that the rows were inserted into the table, you can write a SELECT

statement

Example

SQL> SELECT id, last_name, first_name,

2 userid, start_date, salary

Trang 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć12

Trang 13

Manipulating Data 11Ć13

Inserting Specific Date and Time Values

When inserting a date value, the format DD-MON-YY is usually used With thisformat, recall that the century defaults to the current century Because the date alsocontains time information, the default time is midnight (00:00:00)

If a date is required to be entered in another century and a specific time is also

required, use the TO_DATE function

Example

Record information for the student in the S_EMP table Supply the current user namefor the USERID column Set the START_DATE to be January 1, 1996, 8:00 A.M

SQL> INSERT INTO s_emp (id, first_name,

2 last_name, userid, salary, start_date)

Trang 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć14

Class Management Note:

Be sure to mention the following points about the example:

1 The names of the SQL*Plus substitution parameters do not have to match the corresponding column names

2 Substitution parameters are lexical variables Whatever characters the user enters are substituted as text for the variable name

3 The SQL*Plus SET VERIFY command lists the substitution prior to executing the statement

Trang 15

Manipulating Data 11Ć15

Inserting Values by Using Substitution Variables

You can produce an INSERT command that allows the user to add values

interactively by using SQL*Plus substitution variables

Enter value for department_id: 61

Enter value for department_name: Accounting

Enter value for region_id: 2

1 row created

For date and character values, the ampersand and the variable name are enclosed insingle quotation marks

Trang 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć16

Class Management Note:

Be sure to mention the following points about the script:

1 Do not prefix the SQL*Plus substitution parameter with the ampersand

in the ACCEPT command

2 Use a dash to continue a SQL*Plus command on the next line

3 Add a space after the colon in the PROMPT command

Trang 17

Manipulating Data 11Ć17

Creating a Script to Manipulate Data

You can save your command with substitution variables to a file and execute the file.Each time you execute the command, it will prompt you for new values Customizethe prompts by using the SQL*Plus ACCEPT command

Example

Record information for a department in the S_DEPT table Prompt the user for thedepartment number, department name, and region number Customize the promptmessages

ACCEPT department_id PROMPT ’Please

enter the department number:’

ACCEPT department_name PROMPT ’Please

enter the department name:’

ACCEPT region_id PROMPT ’Please

enter the region number:’

INSERT INTO s_dept (id, name, region_id)

VALUES (&department_id, ’&department_name’,

&region_id);

Please enter the department number: 61

Please enter the department name: Accounting

Please enter the region number: 2

1 row created

Do not prefix the SQL*Plus substitution parameter with the ampersand (&) whenreferencing it in the ACCEPT command Use a dash (-) to continue a SQL*Pluscommand on the next line

Trang 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć18

Trang 19

where: table is the table name.

column is the name of the column in the table to

populate

subquery is the subquery that returns rows into the table.

For more information, see

Oracle7 Server SQL Reference, Release 7.3, “SELECT,” Subqueries section.

Example

Copy selected rows from the S_EMP table into the HISTORY table

SQL> INSERT INTO HISTORY (id, last_name, salary,

Class Management Note:

Please do not get into too many details on copying rows from another table

Trang 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć20

Trang 21

where: table is the table name.

column is the name of the column in the table to

populate

value is the corresponding value or subquery for the

column

condition identifies the rows to be updated and is

composed of column names, expressions,constants, subqueries, and comparisonoperators

Confirm the update operation by querying the table to display the updated rows.For more information, see

Oracle7 Server SQL Reference, Release 7.3, “UPDATE.”

Technical Note:

In general, use the primary key to identify a single row Using other

columns may unexpectedly cause several rows to be updated For example,identifying a single row in the S_EMP table by last name is dangerousbecause several employees may have the same last name

Trang 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć22

Class Management Note:

Trang 23

Confirm both data changes.

SQL> SELECT id, last_name, salary, dept_id

Trang 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć24

Trang 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć26

Trang 27

Manipulating Data 11Ć27

Integrity Constraint Error

If you attempt to update a record with a value that is tied to an integrity constraint,you will experience an error

Trang 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć28

Class Management Note:

The DELETE statement does not ask for confirmation However, the deleteoperation is not made permanent until the data transaction is committed.Therefore, you can undo the operation with the ROLLBACK command ifyou make a mistake

Trang 29

Manipulating Data 11Ć29

Syntax

DELETE [FROM] table

where: table is the table name

condition identifies the rows to be deleted and is

composed of column names, expressions,constants, subqueries, and comparisonoperators

Confirm the delete operation by displaying the deleted rows by using the SELECTcommand

If the WHERE clause is omitted, all rows in the table will be deleted

Example

Remove all information about employees who started after January 1, 1996

SQL> DELETE FROM s_emp

2 WHERE start_date >

3 TO_DATE(’01.01.1996’,’DD.MM.YYYY’);

1 row deleted

For more information, see

Oracle7 Server SQL Reference, Release 7.3, “DELETE.”

Trang 30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć30

Trang 31

Manipulating Data 11Ć31

table will be deleted

Example

Eliminate all data from the TEST table

SQL> DELETE FROM test;

a table is with the TRUNCATE command

You can use the TRUNCATE command to quickly remove all rows from atable or cluster Removing rows with the TRUNCATE command is fasterthan removing them with the DELETE command for the following reasons

The TRUNCATE command is a data definition language command andgenerates no rollback information It will be covered in a later lesson.Truncating a table does not fire the table’s DELETE triggers

If the table is the parent of a referential integrity constraint, you cannottruncate the table if it has child records Disable the constraint before

issuing the TRUNCATE command

Trang 32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć32

Trang 33

Manipulating Data 11Ć33

Integrity Constraint Error

If you attempt to delete a record with a value that is tied to an integrity constraint, youwill experience an error

ORA-02292: integrity constraint

(USR.S_EMP_DEPT_ID_FK) violated - child record found

If the parent record you attempt to delete has child records, then you receive the

“child record found” violation ORA-02292

Technical Note:

If there are referential integrity constraints in use, you might receive anOracle Server error message when you attempt to delete a row However, ifthe referential integrity constraint contains the ON DELETE CASCADEoption, then the selected row and its children are deleted from their

respective tables

Trang 34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć34

Trang 35

Transaction Types

Data manipulation (DML) Consist of any number of DML statements that the

Oracle7 Server treats as a single entity or a logical unit

of work

Data definition (DDL) Consist of only one DDL statement

Data control (DCL) Consists of only one DCL statement

When Does a Transaction Start and End?

A transaction begins when the first executable SQL command is encountered andterminates when one of the following occurs:

D A COMMIT or ROLLBACK command is issued

D A DDL command, such as CREATE, or DCL command is issued

D Certain errors are detected, such as deadlocks

D The user exits SQL*Plus

D A machine fails or the system crashes

After one transaction ends, the next executable SQL statement will automatically startthe next transaction

A DDL command or a DCL command is automatically committed and thereforeimplicitly ends a transaction

Trang 36

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć36

Trang 37

Manipulating Data 11Ć37

Explicit Transaction Control Statements

Control the logic of transactions by using the COMMIT, SAVEPOINT, and

ROLLBACK statements

Command Description

COMMIT Ends the current transaction by making all pending

data changes permanent

SAVEPOINT name Marks a savepoint within the current transaction

Automatic commit DDL command or DCL command is issued

Normal exit from SQL*Plus, without explicitly issuingCOMMIT or ROLLBACK

Automatic rollback Abnormal termination of SQL*Plus, or system failure.Technical Note:

A third command is available The SQL*Plus AUTOCOMMIT commandcan be toggled to be ON or OFF If set to ON, each individual DML

statement is committed as soon as it is executed You cannot roll back thechanges

SAVEPOINT is not ANSI standard SQL

Trang 38

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 11Ć38

Trang 39

Manipulating Data 11Ć39

committed

State of the Data Before COMMIT or ROLLBACK

D Data manipulation operations primarily affect the database buffer; therefore, theprevious state of the data can be recovered

D The current user can review the results of the data manipulation operations byquerying the tables

D Other user cannot view the results of the data manipulation operations for the

current user Oracle7 institutes read consistency to ensure that each user sees data

as it existed at the last commit

D The affected rows are locked; other users cannot change the data within the

affected rows

Technical Note:

Notes for bullets (in order)

With the Oracle7 Server, data changes may actually be written to thedatabase files before COMMIT, but they are still only temporary

If a number of users are making changes simultaneously to the same table,then each user sees only his or her changes until other users commit theirchanges

Other users see data as it is committed in the database (in other words,before changes)

By default, the Oracle7 Server has row-level locking It is possible to alter

the default locking mechanism

Ngày đăng: 21/12/2013, 06:17

TỪ KHÓA LIÊN QUAN

w