Sunteți pe pagina 1din 85

Data Definition

Language DDL
Used to define, alter, drop database objects and privileges
CREATE
ALTER
DROP
RENAME
TRUNCATE
GRANT
REVOKE
COMMENT

Tables an Overview

Uniquely identified by its name and consists of


rows that contain stored info.
Can have up to 254 columns
char(n): Fixed-length character data (string), n
characters long. Occupies space.
varchar2(n): Variable-length character string. The
maximum size for n is 2000.
date: Date data type for storing date and time.
The default format for a date is: DD-MMM-YY.
Examples: 13-OCT-94, 07-JAN-98

Tables an Overview

long: Character data up to a length


of 2GB. Only one long column is
allowed per table.
In Oracle-SQL there is no data type
Boolean. It can, however, be
simulated by using either char(1) or
number(1).

Naming Conventions
Must begin with a letter
Can be 130 characters long
Must contain only AZ, az, 09, _, $,
and #
Must not duplicate the name of another
object owned by the same user
Must not be an Oracle Server reserved
word

The CREATE TABLE Statement


create table <table> (
<column 1> <data type> [not null] [unique]
[DEFAULT defaultOption] [<column constraint>],
.........
);
You need to have
CREATE TABLE privilege and storage
space
Constraints
PRIMARY, REFERENCE, NOT NULL, CHECK

Column level
columnName dataType [NOT NULL] [UNIQUE]
[DEFAULT defaultOption]
CONSTRAINT pk PRIMARY KEY (catalogNo)
CONSTRAINT pk1 PRIMARY KEY (catalogNo, actorNo)
CONSTRAINT fk_deptno REFERENCES scott.dept(deptno)

Table level
PRIMARY KEY (FLT#),
FOREIGN KEY (TO-AIRPORTCODE)
REFERENCES AIRPORT(AIRPORTCODE));
UNIQUE(FLT#, DATE, CUST#),
CHECK (ename = UPPER(ename))

Used to create temperory tables in a SESSION


CREATE GLOBAL TEMPORARY TABLE flight_schedule N COMMIT PRESERVE ROWS;

ENABLE VALIDATE
CREATE TABLE dept (deptno NUMBER (2) PRIMARY KEY DISABLE, dname VARCHAR2(10), loc VARCHAR2(9) );

By default the primary key is enabled and validated

Parallel
The following statement creates a table serially.Subsequent DML and queries on the table will
also be serially executed.
CREATE TABLE emp_dept AS
SELECT * FROM scott.emp WHERE deptno = 10;
Using parallelism speeds up the creation of the table because Oracle uses parallel execution
servers to create the table. After the table is created, querying the table is also faster, because
the same degree of parallelism is used to access the table.
CREATE TABLE emp_dept PARALLEL AS
SELECT * FROM scott.emp WHERE deptno = 10;
The following statement creates a table using 10 parallel execution servers, 5 to scan
SCOTT.EMP and another 5 to populate EMP_DEPT:
CREATE TABLE emp_dept PARALLEL (5) AS
SELECT * FROM scott.emp WHERE deptno = 10;

Partitioned Table
CREATE TABLE stock_xactions (stock_symbol CHAR(5), stock_series CHAR(1),
num_shares NUMBER(10), price NUMBER(5,2), trade_date DATE)
STORAGE (INITIAL 100K NEXT 50K) LOGGING
PARTITION BY RANGE (trade_date)
(PARTITION sx1992 VALUES LESS THAN (TO_DATE('01-JAN-1993','DD-MONYYYY')) TABLESPACE ts0 NOLOGGING,
PARTITION sx1993 VALUES LESS THAN (TO_DATE('01-JAN-1994','DD-MONYYYY')) TABLESPACE ts1,
PARTITION sx1994 VALUES LESS THAN (TO_DATE('01-JAN-1995','DD-MONYYYY')) TABLESPACE ts2);
Storage
A sample table SALGRADE is created in the HUMAN_RESOURCE tablespace with a
small storage capacity and limited allocation potential. The primary key constraint on the
GRADE column and specifies that the index Oracle creates to enforce this constraint is
created in the USERS_A tablespace.
CREATE TABLE salgrade ( grade NUMBER CONSTRAINT pk_salgrade PRIMARY
KEY USING INDEX TABLESPACE users_a, losal NUMBER, hisal NUMBER )
TABLESPACE human_resource
STORAGE (INITIAL 6144 NEXT 6144 MINEXTENTS 1 MAXEXTENTS 5 );

Table Creation
create table UserInfo (
userid number(4) not null,
username varchar2(30) not null,
From_dt date default sysdate,
);
Confirm Table creation
DESCRIBE USERINFO;
Name
Null?
Type
----------------------------------- --------USERID
Not Null NUMBER(4)
USERNAME
Not Null VARCHAR2(30)
FROM_DT
DATE

Tables Overview
User Tables
Collection of tables created and maintained
by the user
Contain user information

Data Dictionary
Collection of tables created and maintained
by the Oracle server
Contain database information
User_tables Tables owned by a user
User_catalog view tables, views,
synonyms, sequences created by an user

Various ways of creating a table

Only the structure -> create table x1


as select * from userinfo where
rownum = 1;
Using subquery for both structure
and data -> create table x1 as select
* from userinfo;

The ALTER TABLE Statement

Use the ALTER TABLE statement to:

Add a new column


Modify an existing column
Define a default value for the new column

Alter table table_name add (column name datatype,..)

Alter table table_name Modify (column name datatype,..)

Adding a Column
USERINFO
USERID USERNAME

HIREDATE

-----7698
7654
7499
7844
...

--------01-MAY-81
28-SEP-81
20-FEB-81
08-SEP-81

---------BLAKE
MARTIN
ALLEN
TURNER

add a
New column new
JOB
column
into
USERINFO
table

USERINFO
USERID
-----7698
7654
7499
7844
...

USERNAME
HIREDATE
---------- -------BLAKE
01-MAY-81
MARTIN
28-SEP-81
ALLEN
20-FEB-81
TURNER
08-SEP-81

JOB

Adding a Column
You use the ADD clause to add columns.
SQL> ALTER TABLE USERINFO
2 ADD
(job VARCHAR2(9));
Table altered.

The new column becomes the last column.


USERID
USERID USERNAME
USERNAME
----------------- ------------------7698
7698 BLAKE
BLAKE
7654
7654 MARTIN
MARTIN
7499
7499 ALLEN
ALLEN
7844
7844 TURNER
TURNER
...
...
66 rows
rows selected.
selected.

HIREDATE
HIREDATE
----------------01-MAY-81
01-MAY-81
28-SEP-81
28-SEP-81
20-FEB-81
20-FEB-81
08-SEP-81
08-SEP-81

JOB
JOB
----------------- -------

Tricks in adding a new column

If column u want to add is NOT


NULL. If there are records already.
Add a new column with null.
Alter table table_name (job
varchar2(9));
Then update the records with some
default value
Finally modify the column to not null
constraint.

Modifying a Column
You can change a columns datatype,
size, and default value.
ALTER TABLE userinfo
MODIFY
(username VARCHAR2(15));
Table altered.

A change to the default value affects


only subsequent insertions to the
table.

Dropping a Table
All data and structure in the table is
deleted.
Any pending transactions are
committed.
All indexes are dropped.
You cannot roll back this statement.
SQL> DROP TABLE userinfo;
Table dropped.

Changing the Name of an


Object
To change the name of a table, view,
sequence, or synonym, you execute
the RENAME statement.
SQL> RENAME dep TO department;
Table renamed.

You must be the owner of the object.

Truncating a Table
The TRUNCATE TABLE statement:

Removes all rows from a table


Releases the storage space used by that
table

SQL> TRUNCATE TABLE department;


Table truncated.

You cannot roll back row removal


when using TRUNCATE.
Alternatively, you can remove rows by
using the DELETE statement.

Constraints
Two Types of constraints:

Column
Column constraints
constraints
not
not null
null
Table
Table constraint
constraint
unique,
unique, primary
primary key
key

Specification is
Constraint <constraint_name> primary key | unique | not null

Constraint Guidelines
Name a constraint or the Oracle Server
will generate a name by using the
SYS_Cn format.
Create a constraint:

At the same time as the table is created


After the table has been created

Define a constraint at the column or


table level.
View a constraint in the data dictionary.

The NOT NULL Constraint


Defined at the column level

SQL> CREATE TABLE


2
empno
3
ename
4
job
5
mgr
6
hiredate
7
sal
8
comm
9
deptno

emp(
NUMBER(4),
VARCHAR2(10) NOT NULL,
VARCHAR2(9),
NUMBER(4),
DATE,
NUMBER(7,2),
NUMBER(7,2),
NUMBER(7,2) NOT NULL);

The UNIQUE Key Constraint


Defined at either the table level or
the column level

SQL> CREATE TABLE


2
deptno
3
dname
4
loc
5
CONSTRAINT

dept(
NUMBER(2),
VARCHAR2(14),
VARCHAR2(13),
dept_dname_uk UNIQUE(dname));

The PRIMARY KEY Constraint


Defined at either the table level or
the column level

SQL> CREATE TABLE


2
deptno
3
dname
4
loc
5
CONSTRAINT
6
CONSTRAINT

dept(
NUMBER(2),
VARCHAR2(14),
VARCHAR2(13),
dept_dname_uk UNIQUE (dname),
dept_deptno_pk PRIMARY KEY(deptno));

Unique constraint allows null values but


primary key constraint does not allow

The FOREIGN KEY Constraint


Defined at either the table level or
the column level

SQL> CREATE TABLE emp(


2
empno
NUMBER(4),
3
ename
VARCHAR2(10) NOT NULL,
4
job
VARCHAR2(9),
5
mgr
NUMBER(4),
6
hiredate DATE,
7
sal
NUMBER(7,2),
8
comm
NUMBER(7,2),
9
deptno
NUMBER(7,2) NOT NULL,
10
CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno)
11
REFERENCES dept (deptno));

FOREIGN KEY Constraint


Keywords
FOREIGN
FOREIGN KEY
KEY
Defines
Defines the
the column
column in
in the
the child
child table
table at
at
the
the table
table constraint
constraint level
level
REFERENCES
REFERENCES
Identifies
Identifies the
the table
table and
and column
column in
in the
the
parent
parent table
table
ON
ON DELETE
DELETE CASCADE
CASCADE
Allows
Allows deletion
deletion in
in the
the parent
parent table
table and
and
deletion
deletion of
of the
the dependent
dependent rows
rows in
in the
the
child
child table
table

The CHECK Constraint


Defines
Defines aa condition
condition that
that each
each row
row must
must
satisfy
satisfy
Expressions
Expressions that
that are
are not
not allowed:
allowed:

References
References to
to CURRVAL,
CURRVAL, NEXTVAL,
NEXTVAL, LEVEL,
LEVEL, and
and
ROWNUM
ROWNUM pseudocolumns
pseudocolumns
Calls
Calls to
to SYSDATE,
SYSDATE, UID,
UID, USER,
USER, and
and USERENV
USERENV
functions
functions
Queries
Queries that
that refer
refer to
to other
other columns
columns in
in other
other
tables
tables

..., deptno NUMBER(2),


CONSTRAINT emp_deptno_ck
CHECK (DEPTNO BETWEEN 10 AND 99),...

Adding a Constraint
Add
Add aa FOREIGN
FOREIGN KEY
KEY constraint
constraint to
to
the
the EMP
EMP table
table indicating
indicating that
that aa
manager
manager must
must already
already exist
exist as
as aa
valid
valid employee
employee in
in the
the EMP
EMP table.
table.

SQL> ALTER TABLE


emp
2 ADD CONSTRAINT emp_mgr_fk
3
FOREIGN KEY(mgr) REFERENCES emp(empno);
Table altered.

Dropping a Constraint
Remove the manager constraint from
the EMP table.

SQL>
emp
SQL> ALTER
ALTER TABLE
TABLE
emp
22 DROP
DROP CONSTRAINT
CONSTRAINT emp_mgr_fk;
emp_mgr_fk;
Table
Table altered.
altered.

Remove the PRIMARY KEY constraint


on the DEPT table and drop the
associated FOREIGN KEY constraint on
the EMP.DEPTNO column.
SQL>
dept
SQL> ALTER
ALTER TABLE
TABLE
dept
22 DROP
DROP PRIMARY
PRIMARY KEY
KEY CASCADE;
CASCADE;
Table
Table altered.
altered.

Disabling Constraints
Execute the DISABLE clause of the
ALTER TABLE statement to deactivate
an integrity constraint.
Apply the CASCADE option to disable
dependent integrity constraints.
SQL>
SQL> ALTER
ALTER TABLE
TABLE
22 DISABLE
DISABLE CONSTRAINT
CONSTRAINT
Table
Table altered.
altered.

emp
emp
emp_empno_pk
emp_empno_pk CASCADE;
CASCADE;

Enabling Constraints
Activate an integrity constraint
currently disabled in the table
definition by using the ENABLE clause.
SQL>
SQL> ALTER
ALTER TABLE
TABLE
22 ENABLE
ENABLE CONSTRAINT
CONSTRAINT
Table
Table altered.
altered.

emp
emp
emp_empno_pk;
emp_empno_pk;

A UNIQUE or PRIMARY KEY index is


automatically created if you enable a
UNIQUE key or PRIMARY KEY
constraint.

Viewing Constraints
Query the USER_CONSTRAINTS table to view
all constraint definitions and names.

SQL>
2
3
4

SELECT constraint_name, constraint_type,


search_condition
FROM
user_constraints
WHERE table_name = 'EMP';

CONSTRAINT_NAME
CONSTRAINT_NAME
----------------------------------------------SYS_C00674
SYS_C00674
SYS_C00675
SYS_C00675
EMP_EMPNO_PK
EMP_EMPNO_PK
...
...

CC
-CC
CC
PP

SEARCH_CONDITION
SEARCH_CONDITION
------------------------------------------------EMPNO
EMPNO IS
IS NOT
NOT NULL
NULL
DEPTNO
DEPTNO IS
IS NOT
NOT NULL
NULL

Viewing the Columns


Associated with Constraints

View
View the
the columns
columns associated
associated with
with the
the
constraint
constraint names
names in
in the
the USER_CONS_COLUMNS
USER_CONS_COLUMNS
view.
view.

SQL> SELECT
2 FROM
3 WHERE

constraint_name, column_name
user_cons_columns
table_name = 'EMP';

CONSTRAINT_NAME
CONSTRAINT_NAME
------------------------------------------------EMP_DEPTNO_FK
EMP_DEPTNO_FK
EMP_EMPNO_PK
EMP_EMPNO_PK
EMP_MGR_FK
EMP_MGR_FK
SYS_C00674
SYS_C00674
SYS_C00675
SYS_C00675

COLUMN_NAME
COLUMN_NAME
------------------------------------------DEPTNO
DEPTNO
EMPNO
EMPNO
MGR
MGR
EMPNO
EMPNO
DEPTNO
DEPTNO

Data Manipulation Language


A DML statement is executed when
you:

Add new rows to a table


Modify existing rows in a table
Remove existing rows from a table

A transaction consists of a collection


of DML statements that form a logical
unit of work.

Adding a New Row to a Table


50 DEVELOPMENT DETROIT

New row
DEPT
DEPTNO
-----10
20
30
40

DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS

LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON

insert a new row


into DEPT table
DEPT
DEPTNO
-----10
20
30
40

DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS

LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON

50 DEVELOPMENT DETROIT

Inserting Rows with Null Values


Implicit method: Omit the column
from the column list.
SQL> INSERT INTO
2 VALUES
1 row created.

dept (deptno, dname )


(60, 'MIS');

Explicit method: Specify the NULL


keyword.
SQL> INSERT INTO
2 VALUES
1 row created.

dept
(70, 'FINANCE', NULL);

Inserting Special Values


The SYSDATE function records the
current date and time.

SQL> INSERT INTO


2
3
4 VALUES
5
6
1 row created.

emp (empno, ename, job,


mgr, hiredate, sal, comm,
deptno)
(7196, 'GREEN', 'SALESMAN',
7782, SYSDATE, 2000, NULL,
10);

Inserting Specific Date Values


Add a new employee.
SQL> INSERT INTO
2 VALUES
3
4
1 row created.

emp
(2296,'AROMANO','SALESMAN',7782,
TO_DATE('FEB 3, 97', 'MON DD, YY'),
1300, NULL, 10);

Verify your addition.


EMPNO ENAME
JOB
MGR
HIREDATE SAL COMM DEPTNO
----- ------- -------- ---- --------- ---- ---- -----2296 AROMANO SALESMAN 7782 03-FEB-97 1300
10

Inserting Values by Using


Substitution Variables

Create an interactive script by using


SQL*Plus substitution parameters.

SQL> INSERT INTO


2 VALUES
3

dept (deptno, dname, loc)


(&department_id,
'&department_name', '&location');

Enter value for department_id: 80


Enter value for department_name: EDUCATION
Enter value for location: ATLANTA
1 row created.

Creating a Script
with Customized Prompts

ACCEPT stores the value in a variable.


PROMPT displays your customized text.
ACCEPT

department_id PROMPT 'Please enter the department number:'

ACCEPT

department_name PROMPT 'Please enter the department name:'

ACCEPT

location PROMPT 'Please enter the location:'

INSERT INTO

dept (deptno, dname, loc)

VALUES

(&department_id, '&department_name',
'&location');

Copying Rows
from Another Table
Write your INSERT statement with a
subquery.
SQL> INSERT INTO managers(id, name, salary, hiredate)
2
SELECT empno, ename, sal, hiredate
3
FROM
emp
4
WHERE job = 'MANAGER';
3 rows created.

Do not use the VALUES clause.


Match the number of columns in the
INSERT clause to those in the
subquery.

Changing Data in a Table


EMP
EMPNO ENAME
7839
7698
7782
7566
...

KING
BLAKE
CLARK
JONES

JOB

...

DEPTNO

PRESIDENT
MANAGER
MANAGER
MANAGER

10
30
10
20

update a row
in EMP table

EMP
EMPNO ENAME
7839
7698
7782
7566
...

KING
BLAKE
CLARK
JONES

JOB
PRESIDENT
MANAGER
MANAGER
MANAGER

...

DEPTNO
10
30
20
10
20

Updating with
Multiple-Column Subquery
Update employee 7698s job and department to
match that of employee 7499.

SQL> UPDATE emp


2 SET
(job, deptno) =
3
(SELECT job, deptno
4
FROM
emp
5
WHERE
empno = 7499)
6 WHERE
empno = 7698;
1 row updated.

Updating Rows Based


on Another Table

Use subqueries in UPDATE statements


to update rows in a table based on
values from another table.

SQL>
SQL> UPDATE
UPDATE employee
employee
22 SET
deptno
SET
deptno == (SELECT
(SELECT
33
FROM
FROM
44
WHERE
WHERE
55 WHERE
job
== (SELECT
WHERE
job
(SELECT
66
FROM
FROM
77
WHERE
WHERE
22 rows
rows updated.
updated.

deptno
deptno
emp
emp
empno
empno ==
job
job
emp
emp
empno
empno ==

7788)
7788)
7788);
7788);

Integrity constraint Errors


When the key value is not found in the
parent table
Emp is the parent table for dep table.
Emp does not have a record say 100.
When you update dep table, update
dep set empid =100 where
empid=10; -> Retrieves ERROR.

Removing a Row from a Table


DEPT
DEPTNO
-----10
20
30
40
50
60
...

DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS

LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON
DEVELOPMENT DETROIT
MIS

delete a row
from DEPT table
DEPT
DEPTNO
-----10
20
30
40
60
...

DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS
MIS

LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON

Deleting Rows Based


on Another Table

Use subqueries in DELETE statements


to remove rows from a table based on
values from another table.

SQL> DELETE FROM


2 WHERE
3
4
5
6 rows deleted.

employee
deptno =
(SELECT
FROM
WHERE

deptno
dept
dname ='SALES');

Data Control Language


DCL
Used to control the transactions in a session or database
connection and is mainly called Transaction Control
Language
COMMIT
ROLLBACK
SAVEPOINT
SET TRANSACTION

Advantages of COMMIT
and ROLLBACK Statements
Ensure data consistency
Preview data changes before making
changes permanent
Group logically related operations

Controlling Transactions
Transaction
INSERT
COMMIT

UPDATE

Savepoint A

INSERT

DELETE

Savepoint B

ROLLBACK to Savepoint B

ROLLBACK to Savepoint A

ROLLBACK

Implicit Transaction Processing


An automatic commit occurs under
the following circumstances:

DDL statement is issued


DCL statement is issued
Normal exit from SQL*Plus, without
explicitly issuing COMMIT or ROLLBACK

An automatic rollback occurs under


an abnormal termination of SQL*Plus
or a system failure.

State of the Data Before


COMMIT or ROLLBACK
The previous state of the data can be
recovered.
The current user can review the results of
the DML operations by using the SELECT
statement.
Other users cannot view the results of the
DML statements by the current user.
The affected rows are locked; other users
cannot change the data within the affected
rows.

State of the Data After COMMIT


Data changes are made permanent in
the database.
The previous state of the data is
permanently lost.
All users can view the results.
Locks on the affected rows are released;
those rows are available for other users
to manipulate.
All savepoints are erased.

Committing Data
Make the changes.
SQL>
SQL> UPDATE
UPDATE emp
emp
22 SET
deptno
SET
deptno == 10
10
33 WHERE
empno
WHERE
empno == 7782;
7782;
11 row
row updated.
updated.

Commit the changes.


SQL> COMMIT;
Commit complete.

State of the Data After


ROLLBACK
Discard all pending changes by using the
ROLLBACK statement.
Data changes are undone.
Previous state of the data is restored.
Locks on the affected rows are released.

SQL> DELETE FROM


14 rows deleted.
SQL> ROLLBACK;
Rollback complete.

employee;

Rolling Back Changes


to a Marker
Create a marker in a current transaction by
using the SAVEPOINT statement.
Roll back to that marker by using the
ROLLBACK TO SAVEPOINT statement.
SQL> UPDATE...
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT...
SQL> ROLLBACK TO update_done;
Rollback complete.

Implementation of Read
Consistency
Data
blocks

UPDATE emp
SET
sal = 2000
WHERE ename =
'SCOTT';

Rollback
segments

User A
SELECT *
FROM
emp;

User B

Read
consistent
image

changed
and
unchanged
data
before
change
old data

Using the SET VERIFY


Command
Toggling the display of the text of a command
before and after SQL*Plus replaces substitution
variables with values.

SQL>
SQL>
2
3

SET VERIFY ON
SELECT empno, ename, sal, deptno
FROM
emp
WHERE
empno = &employee_num;

Enter value for employee_num: 7369


old
3: WHERE empno = &employee_num
new
3: WHERE empno = 7369
...

Character and Date Values


with Substitution Variables

Use single quotation marks for date


and character values.

SQL> SELECT ename, deptno, sal*12


2 FROM
emp
3 WHERE job='&job_title';
Enter value for job_title: ANALYST
ENAME
DEPTNO
SAL*12
---------- --------- --------SCOTT
20
36000
FORD
20
36000

Specifying Column Names,


Expressions, and Text at
Runtime
Use substitution variables to
supplement the following:

WHERE condition
ORDER BY clause
Column expression
Table name
Entire SELECT statement

Specifying Column Names, Expressions, and


Text at Runtime
SQL>
2
3
4

SELECT
FROM
WHERE
ORDER BY

empno, ename, job, &column_name


emp
&condition
&order_column;

Enter value for column_name: sal


Enter value for condition: sal>=3000
Enter value for order_column: ename
EMPNO
--------7902
7839
7788

ENAME
---------FORD
KING
SCOTT

JOB
SAL
--------- --------ANALYST
3000
PRESIDENT
5000
ANALYST
3000

Using the && Substitution Variable


Use the double-ampersand (&&) if you want to reuse the
variable value without prompting the user each time.

SQL> SELECT
2 FROM
3 ORDER BY

empno, ename, job, &&column_name


emp
&column_name;

Enter value for column_name: deptno


EMPNO ENAME
JOB
DEPTNO
--------- ---------- --------- --------7839 KING
PRESIDENT
10
7782 CLARK
MANAGER
10
7934 MILLER
CLERK
10
...
14 rows selected.

Defining User Variables


You can predefine variables using one
of two SQL*Plus commands:

DEFINE: Create a CHAR datatype user


variable
ACCEPT: Read user input and store it in a
variable

If you need to predefine a variable


that includes spaces, you must
enclose the value within single
quotation marks when using the
DEFINE command.

The ACCEPT Command


Creates a customized prompt when
accepting user input
Explicitly defines a NUMBER or DATE
datatype variable
Hides user input for security reasons
ACCEPT
ACCEPT variable
variable [datatype]
[datatype] [FORMAT
[FORMAT format]
format]
[PROMPT
[PROMPT text]
text] [HIDE]
[HIDE]

Using the ACCEPT Command


ACCEPT
SELECT
FROM
WHERE
/

dept PROMPT 'Provide the department name: '


*
dept
dname = UPPER('&dept')

Provide the department name: Sales


DEPTNO DNAME
LOC
--------- -------------- ------------30 SALES
CHICAGO

DEFINE and UNDEFINE Commands

A variable remains defined until you


either:

Use the UNDEFINE command to clear it


Exit SQL*Plus

You can verify your changes with the


DEFINE command.
To define variables for every session,
modify your login.sql file so that the
variables are created at startup.

Using the DEFINE Command


Create a variable to hold the
department name.
SQL> DEFINE deptname = sales
SQL> DEFINE deptname
DEFINE
DEFINE DEPTNAME
DEPTNAME

== "sales"
"sales" (CHAR)
(CHAR)

Use the variable as you would any other


variable.
SQL> SELECT *
2 FROM
dept
3 WHERE dname = UPPER('&deptname');

Basic SELECT Statement


SELECT
SELECT
FROM
FROM

[DISTINCT]
[DISTINCT] {*,
{*, column
column [alias],...}
[alias],...}
table;
table;

SELECT identifies what columns.


FROM identifies which table.

Writing SQL Statements


SQL statements are not case
sensitive.
SQL statements can be on one or
more lines.
Keywords cannot be abbreviated or
split across lines.
Clauses are usually placed on
separate lines.
Tabs and indents are used to enhance
readability.

Selecting All Columns


SQL> SELECT *
2 FROM
dept;
DEPTNO
--------10
20
30
40

DNAME
-------------ACCOUNTING
RESEARCH
SALES
OPERATIONS

LOC
------------NEW YORK
DALLAS
CHICAGO
BOSTON

Selecting Specific Columns


SQL> SELECT deptno, loc
2 FROM
dept;
DEPTNO
--------10
20
30
40

LOC
------------NEW YORK
DALLAS
CHICAGO
BOSTON

Defining a Null Value


A null is a value that is unavailable,
unassigned, unknown, or inapplicable.
A null is not the same as zero or a blank
space.
SQL> SELECT
2 FROM

ename, job, comm


emp;

ENAME
JOB
COMM
---------- --------- --------KING
PRESIDENT
BLAKE
MANAGER
...
TURNER
SALESMAN
0
...
14 rows selected.

About PL/SQL
PL/SQL is an extension to SQL with
design features of programming
languages.
Data manipulation and query
statements of SQL are included within
procedural units of code.

Benefits of PL/SQL
Improved Performance

SQL

Application
Application

SQL
SQL

Other
Other DBMSs
DBMSs

SQL

Application
Application

SQL
IF...THEN
SQL
ELSE
SQL
END IF;
SQL

Oracle
Oracle with
with
PL/SQL
PL/SQL

Benefits of PL/SQL
Modularize program development

DECLARE

BEGIN

EXCEPTION

END;

Benefits of PL/SQL
It is portable.
You can declare identifiers.

Benefits of PL/SQL
You can program with procedural
language control structures.
It can handle errors.

PL/SQL Block Structure


DECLARE
DECLARE Optional
Optional

Variables,
Variables,cursors,
cursors,user-defined
user-defined
exceptions
exceptions

BEGIN
BEGIN Mandatory
Mandatory

SQL
SQLstatements
statements
PL/SQL
PL/SQLstatements
statements

EXCEPTION
EXCEPTION Optional
Optional

Actions
Actionsto
toperform
performwhen
when
errors
errorsoccur
occur

END;
END; Mandatory
Mandatory

DECLARE
BEGIN
EXCEPTION
END;

PL/SQL Block Structure


DECLARE
DECLARE
v_variable
v_variable VARCHAR2(5);
VARCHAR2(5);
BEGIN
BEGIN
SELECT
column_name
SELECT
column_name
INTO
v_variable
INTO
v_variable
FROM
table_name;
FROM
table_name;
EXCEPTION
EXCEPTION
WHEN
WHEN exception_name
exception_name THEN
THEN
...
...
END;
END;

DECLARE
BEGIN
EXCEPTION
END;

Block Types

Anonymous

Procedure Function

[DECLARE]
[DECLARE]

PROCEDURE
PROCEDURE name
name
IS
IS

BEGIN
BEGIN
--statements
--statements

BEGIN
BEGIN
--statements
--statements

[EXCEPTION]
[EXCEPTION]

[EXCEPTION]
[EXCEPTION]

FUNCTION
FUNCTION name
name
RETURN
RETURN datatype
datatype
IS
IS
BEGIN
BEGIN
--statements
--statements
RETURN
RETURN value;
value;
[EXCEPTION]
[EXCEPTION]

END;
END;

END;
END;

END;
END;

Use of Variables
Use variables for:

Temporary storage of data


Manipulation of stored values
Reusability
Ease of maintenance

Handling Variables in PL/SQL


Declare and initialize variables in the
declaration section.
Assign new values to variables in the
executable section.
Pass values into PL/SQL blocks
through parameters.
View results through output variables.

Scalar Variable Declarations


Examples

v_job
v_job
v_count
v_count
v_total_sal
v_total_sal
v_orderdate
v_orderdate
c_tax_rate
c_tax_rate
v_valid
v_valid

VARCHAR2(9);
VARCHAR2(9);
BINARY_INTEGER
BINARY_INTEGER :=
:= 0;
0;
NUMBER(9,2)
NUMBER(9,2) :=
:= 0;
0;
DATE
DATE :=
:= SYSDATE
SYSDATE ++ 7;
7;
CONSTANT
NUMBER(3,2)
CONSTANT NUMBER(3,2) :=
:= 8.25;
8.25;
BOOLEAN
BOOLEAN NOT
NOT NULL
NULL :=
:= TRUE;
TRUE;

The %TYPE Attribute


Declare a variable according to:

A database column definition


Another previously declared variable

Prefix %TYPE with:

The database table and column


The previously declared variable name

Declaring Variables
with the %TYPE Attribute
Examples

...
...
v_ename
v_ename
v_balance
v_balance
v_min_balance
v_min_balance
...
...

emp.ename%TYPE;
emp.ename%TYPE;
NUMBER(7,2);
NUMBER(7,2);
v_balance%TYPE
v_balance%TYPE :=
:= 10;
10;

S-ar putea să vă placă și