Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
SQL Overview
SQL Statements
SELECT INSERT UPDATE DELETE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT GRANT REVOKE
Copyright 2004, Oracle. All rights reserved.
Transaction control
Primary key
Copyright 2004, Oracle. All rights reserved.
Foreign key
Foreign key
DEPT Tables
DEPT
DEPTNO DNAME LOC --------- -------------- ---------10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS NEW YORK DALLAS CHICAGO BOSTON
Primary key
Table 1
Table 1
Join
Table 1
Copyright 2004, Oracle. All rights reserved.
Table 2
SELECT identifies the columns to be displayed. SELECT identifies the columns to be displayed. FROM identifies the table that contains the columns. FROM identifies the table that contains the columns.
SQL statements are not case sensitive. SQL statements are not case sensitive. SQL statements can be on one or SQL statements can be on one or more lines. more lines. Keywords cannot be abbreviated or split across lines. Keywords cannot be abbreviated or split across lines. Clauses are usually placed on Clauses are usually placed on separate lines. separate lines. Tabs and indents are used to enhance readability. Tabs and indents are used to enhance readability.
DEPT
DEPTNO DNAME 10 20 30 40 ACCOUNTING RESEARCH SALES OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON
DEPTNO --------10 20 30 40
DEPT
DEPTNO LOC 10 20 30 40 NEW YORK DALLAS CHICAGO BOSTON
EMP ENAME HIREDATE SAL ---------- --------- --------KING 17-NOV-81 5000 BLAKE 01-MAY-81 2850 CLARK 09-JUN-81 2450 JONES 02-APR-81 2975 MARTIN 28-SEP-81 1250 ALLEN 20-FEB-81 1600 ... 14 rows selected.
Arithmetic Expressions
Create expressions on NUMBER and DATE data Create expressions on NUMBER and DATE data types by using arithmetic operators. types by using arithmetic operators.
Operator + * /
Operator Precedence
/ +
Multiplication and division take priority over addition Multiplication and division take priority over addition and subtraction. and subtraction. Operators of the same priority are evaluated from left to Operators of the same priority are evaluated from left to right. right. Parentheses are used to force prioritized evaluation Parentheses are used to force prioritized evaluation and to clarify statements. and to clarify statements.
Operator Precedence
SQL> SELECT ename, sal, 12*sal+100 2 FROM emp; ENAME SAL 12*SAL+100 ---------- --------- ---------KING 5000 60100 BLAKE 2850 34300 CLARK 2450 29500 JONES 2975 35800 MARTIN 1250 15100 ALLEN 1600 19300 ... 14 rows selected.
Using Parentheses
SQL> SELECT ename, sal, 12*(sal+100) 2 FROM emp; ENAME SAL 12*(SAL+100) ---------- --------- ----------KING 5000 61200 BLAKE 2850 35400 CLARK 2450 30600 JONES 2975 36900 MARTIN 1250 16200 ... 14 rows selected.
Renames a column heading Renames a column heading Is useful with calculations Is useful with calculations Immediately follows column name; optional AS Immediately follows column name; optional AS keyword between column name and alias keyword between column name and alias Requires double quotation marks if it is case sensitive Requires double quotation marks if it is case sensitive or contains spaces or special characters or contains spaces or special characters
SQL> SELECT ename AS name, sal salary 2 FROM emp; NAME SALARY ------------- --------KING 5000 BLAKE 2850 CLARK 2450 JONES 2975 ... 14 rows selected.
SQL> SELECT ename "Name", 2 sal*12 "Annual Salary" 3 FROM emp; Name Annual Salary ------------- ------------KING 60000 BLAKE 34200 CLARK 29400 ... 14 rows selected.
Concatenation Operator
Concatenates columns or character strings to other Concatenates columns or character strings to other columns columns Is represented by two vertical bars || Is represented by two vertical bars || Creates a result column that is a character expression Creates a result column that is a character expression
Employees ------------------KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER MARTINSALESMAN ALLENSALESMAN ... 14 rows selected.
Literals
A literal is a constant value of character, expression, or A literal is a constant value of character, expression, or number that can be included in the SELECT list. number that can be included in the SELECT list. Date and character literal values must be enclosed in Date and character literal values must be enclosed in single quotation marks. single quotation marks. Each character string is output once for each row Each character string is output once for each row returned. returned.
Duplicate Rows
The default display of queries is all rows, including The default display of queries is all rows, including duplicate rows. duplicate rows.
SQL> SELECT 2 FROM deptno emp;
DEPTNO --------10 20 30
EMP
EMPNO ENAME JOB ... DEPTNO 10 10 10
Character strings and date values are enclosed in Character strings and date values are enclosed in single quotation marks. single quotation marks. Character values are case sensitive and date values Character values are case sensitive and date values are format sensitive. are format sensitive. Default date format is DD-MON-YY. Default date format is DD-MON-YY.
Comparison Operators
Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
ENAME SAL ---------- --------MARTIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300
Lower limit
Higher limit
ENAME SAL MGR ---------- --------- --------FORD 3000 7566 SMITH 800 7902 SCOTT 3000 7566 ADAMS 1100 7788
Use the LIKE operator to perform wildcard searches of Use the LIKE operator to perform wildcard searches of valid search string values. valid search string values. Search conditions can contain either literal characters Search conditions can contain either literal characters or numbers. or numbers.
% denotes zero or many characters % denotes zero or many characters _ denotes one character _ denotes one character
Use the ESCAPE identifier to search for Use the ESCAPE identifier to search for % or _. % or _.
Copyright 2004, Oracle. All rights reserved.
Logical Operators
Operator AND OR
Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns TRUE if the following condition is FALSE
NOT
ENAME MGR SAL DEPTNO ---------- --------- --------- --------KING 5000 10 CLARK 7839 2450 10 MILLER 7782 1300 10
EMPNO ENAME --------- ---------7839 KING 7698 BLAKE 7782 CLARK 7566 JONES 7900 JAMES 7902 FORD ... 10 rows selected.
Copyright 2004, Oracle. All rights reserved.
SQL> 2 3 4
DEPTNO -------10 30 10 20 10
EMPNO ENAME DEPTNO MGR --------- ---------- --------- --------7654 MARTIN 30 7698 7499 ALLEN 30 7698 ... ... 7902 FORD 20 7566 7369 SMITH 20 7902 ... 10 rows selected.
ENAME Salary Before Commission COMM ---------- ------------------------ --------MARTIN 1250 1400 ALLEN 1600 300 TURNER 1500 0 WARD 1250 500
Rules of Precedence
Order Evaluated 1 2 3 4 Operator All comparison operators NOT AND OR
Use parentheses to override rules of precedence. Use parentheses to override rules of precedence.
Rules of Precedence
SQL> 2 3 4 5 SELECT FROM WHERE OR AND ename, job, sal emp job='SALESMAN' job='PRESIDENT' sal>1500;
Rules of Precedence
Use parentheses to force priority. Use parentheses to force priority.
SQL> 2 3 4 5 SELECT FROM WHERE OR AND ename, job, sal emp (job='SALESMAN' job='PRESIDENT') sal>1500;
ORDER BY Clause
Sort rows with the ORDER BY clause: Sort rows with the ORDER BY clause:
ASC: ascending order, default ASC: ascending order, default DESC: descending order DESC: descending order
The ORDER BY clause comes last in the SELECT The ORDER BY clause comes last in the SELECT statement. statement.
SQL> SELECT ename, job, deptno 2 FROM emp 3 ORDER BY deptno; ENAME JOB DEPTNO ---------- --------- --------KING PRESIDENT 10 CLARK MANAGER 10 ... JONES MANAGER 20 SCOTT ANALYST 20 ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.
ENAME JOB DEPTNO SAL ---------- --------- --------- --------KING PRESIDENT 10 5000 FORD ANALYST 20 3000 SCOTT ANALYST 20 3000 JONES MANAGER 20 2975 BLAKE MANAGER 30 2850 CLARK MANAGER 10 2450 ALLEN SALESMAN 30 1600 ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.
EMPNO ENAME ANNSAL --------- ---------- --------7369 SMITH 9600 7900 JAMES 11400 7876 ADAMS 13200 7654 MARTIN 15000 7521 WARD 15000 7934 MILLER 15600 7844 TURNER 18000 ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.
Input
Output
Functions
Single-row functions
Multiple-row functions
Single-Row Functions
Manipulate data items Manipulate data items Accept arguments and return one value Accept arguments and return one value Act on each row returned Act on each row returned Return one result per row Return one result per row Can modify the data type Can modify the data type Can be nested Can be nested
Single-Row Functions
Character Number
Single-row functions
Conversion
Date
Character Functions
Character functions
Number Functions
ROUND: Rounds value to specified decimal ROUND: Rounds value to specified decimal ROUND(45.926, 2) ROUND(45.926, 2) 45.93 45.93 TRUNC: Truncates value to specified decimal TRUNC: Truncates value to specified decimal TRUNC(45.926, 2) TRUNC(45.926, 2) 45.92 45.92 MOD: Returns remainder of division MOD: Returns remainder of division MOD(1600, 300) MOD(1600, 300) 100 100
A null is a value that is unavailable, unassigned, A null is a value that is unavailable, unassigned, unknown, or inapplicable. unknown, or inapplicable. A null is not the same as zero or a blank space. A null is not the same as zero or a blank space.
ENAME JOB COMM ---------- --------- --------KING PRESIDENT BLAKE MANAGER ... TURNER SALESMAN 0 ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.
Use the NVL function to force a value where a null Use the NVL function to force a value where a null would otherwise appear: would otherwise appear:
NVL can be used with date, character, and number NVL can be used with date, character, and number data types. data types. Data types must match. For example: Data types must match. For example:
NVL(comm,0) NVL(comm,0) NVL(hiredate,'01-JAN-97') NVL(hiredate,'01-JAN-97') NVL(job,'no job yet') NVL(job,'no job yet' yet')
Single-Row Functions
Character Number
Single-row functions
Conversion
Date
Oracle stores dates in an internal 7 byte numeric format: Oracle stores dates in an internal 7 byte numeric format: century, year, month, day, hours, minutes, seconds. century, year, month, day, hours, minutes, seconds. The default date format is DD-MON-YY. The default date format is DD-MON-YY.
SYSDATE
Use SYSDATE to display the current date and time. Use SYSDATE to display the current date and time. DUAL is a one-column, one-row table that is used as a DUAL is a one-column, one-row table that is used as a dummy table. dummy table.
Add or subtract a number to or from a date to obtain a date Add or subtract a number to or from a date to obtain a date value value Subtract two dates to find the number of days between Subtract two dates to find the number of days between those dates those dates
NUMBER
CHARACTER
DATE
TO_CHAR
TO_CHAR
Tuesday the 27th of January, 1998 27-JAN-98 January 27, 1998 01/27/98
Is case sensitive and must be enclosed in single Is case sensitive and must be enclosed in single quotation marks quotation marks Can include any valid date format element Can include any valid date format element Has an fm element to remove padded blanks or Has an fm element to remove padded blanks or suppress leading zeros suppress leading zeros Is separated from the date value by a comma Is separated from the date value by a comma
---------- --------------------
ENAME HIREDATE ---------- ----------------KING 17 November 1981 BLAKE 1 May 1981 CLARK 9 June 1981 JONES 2 April 1981 MARTIN 28 September 1981 ALLEN 20 February 1981 ... 14 rows selected.
ENAME MGR SAL HIREDATE ---------- --------- --------- ----------SMITH 7902 800 1980-DEC-17
ENAME DEPTNO HIREDATE ---------- --------- ----------SMITH 20 12-17-1980 SCOTT 20 12-09-1982 ADAMS 20 01-12-1983 MILLER 10 01-23-1982
ENAME JOB DEPTNO HIRE_DATE ---------- --------- --------- ----------ADAMS CLERK 20 12-JAN-1983 SCOTT ANALYST 20 09-DEC-1982 MILLER CLERK 10 23-JAN-1982 JAMES CLERK 30 03-DEC-1981 FORD ANALYST 20 03-DEC-1981 KING PRESIDENT 10 17-NOV-1981 MARTIN SALESMAN 30 28-SEP-1981 ... 14 rows selected.
HH24:MI:SS AM
DD "of" MONTH
12 of OCTOBER
ddspth
fourteenth
TIME -------13:55:46
9 0 $ L . ,
Represents a number Forces a zero to be displayed Places a floating dollar sign Uses the floating local currency symbol Prints a decimal point Places a thousand indicator
SALARY -------$3,000
Convert a character string to a number data type using the Convert a character string to a number data type using the TO_NUMBER function TO_NUMBER function
TO_NUMBER(char)
Convert a character string to a date data Convert a character string to a date data type using the TO_DATE function type using the TO_DATE function
TO_DATE(char[, 'fmt'])
NEW_SALARY ---------4000
Date Functions
FUNCTION MONTHS_BETWEEN ADD_MONTHS NEXT_DAY LAST_DAY ROUND TRUNC DESCRIPTION Number of months between two dates Adds calendar months to date Next day following the date specified Last day of the month Round off date Truncate date
Nesting Functions
Single-row functions can be nested to any level. Single-row functions can be nested to any level. Nested functions are evaluated from the innermost level to Nested functions are evaluated from the innermost level to the outermost level. the outermost level.
F3(F2(F1(col,arg1),arg2),arg3)
Step 1 = Result 1 Step 2 = Result 2 Step 3 = Result 3
Nesting Functions
Result 1
SQL> SELECT 2 3 FROM 4 WHERE
Result 2
Nesting Functions
SQL> SELECT MONTHS_BETWEEN 2 (TO_DATE('02-02-1995','MM-DD-YYYY'), 3 TO_DATE('01-01-1995','MM-DD-YYYY')) 4 "Months" 5 FROM DUAL;
Months ---------1.03225806
Obtaining Data from Multiple Tables Obtaining Data from Multiple Tables
EMP
EMPNO -----7839 7698 ... 7934 ENAME ----KING BLAKE ... DEPTNO ... -----... 10 ... 30 10
DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
MILLER ...
DEPTNO ------10 30 10 20 30 30
Joining Tables
Use a join to query data from more than one table: Use a join to query data from more than one table:
SELECT table1.column1, table2.column2 FROM table1, table2 WHERE Write the join condition in the WHERE clause. table1.column1 = table2.column2; Write the join condition in the WHERE clause.
Prefix the column name with the table name when the Prefix the column name with the table name when the same column name appears in more than one table. same column name appears in more than one table.
Types of Joins
Equijoin Nonequijoin Self join Equijoin Nonequijoin Self join
What Is an Equijoin?
EMP
EMPNO ENAME DEPTNO ------ ------- ------... 7782 CLARK 10
DEPT
DEPTNO DNAME LOC ------- ---------- -------... 10 ACCOUNTING NEW YORK ...
WHERE emp.deptno=dept.deptno
Equijoin
EMP
EMPNO ENAME DEPTNO ------ ------- ------7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20 ... 14 rows selected. Foreign key
Copyright 2004, Oracle. All rights reserved.
DEPT
DEPTNO ------10 30 10 20 30 30 30 30 30 20 20 ... 14 rows DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH SALES SALES SALES SALES SALES RESEARCH RESEARCH selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO DALLAS DALLAS
Primary key
EMPNO ENAME DEPTNO DEPTNO LOC ----- ------ ------ ------ --------7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS ... 14 rows selected.
Use table prefixes to qualify column names that are in Use table prefixes to qualify column names that are in multiple tables. multiple tables. Use table prefixes to improve performance. Use table prefixes to improve performance.
DEPT
DEPTNO DNAME ------ --------10 ACCOUNTING 30 SALES 10 ACCOUNTING 20 RESEARCH 30 SALES 30 SALES 30 SALES 30 SALES ... 14 rows selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO
EMPNO ENAME DEPTNO LOC --------- ---------- --------- ------------7839 KING 10 NEW YORK
JOB DEPTNO DNAME --------- --------- -------------PRESIDENT 10 ACCOUNTING MANAGER 30 SALES MANAGER 10 ACCOUNTING MANAGER 20 RESEARCH
Table Aliases
Simplify queries by using table aliases. Simplify queries by using table aliases.
SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno;
14 rows selected.
Nonequijoins
EMP
EMPNO ENAME SAL ------ ------- -----7839 KING 5000 7698 BLAKE 2850 7782 CLARK 2450 7566 JONES 2975 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 ... 14 rows selected.
SALGRADE
GRADE LOSAL HISAL ----- ----- -----1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999
Salary in the EMP table is between low salary and high salary in the SALGRADE table.
ENAME SAL GRADE ---------- --------- --------JAMES 950 1 SMITH 800 1 ADAMS 1100 1 ... 14 rows selected.
DEPT
DEPTNO DNAME --------- ---------10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS
SALGRADE
LOSAL HISAL GRADE --------- --------- --------700 1200 1 WHERE emp.sal BETWEEN 1201 1400 2 salgrade.losal AND 1401 2000 3 2001 3000 4 salgrade.hisal 3001 9999 5 AND emp.deptno = dept.deptno
Copyright 2004, Oracle. All rights reserved.
ENAME DEPTNO ---------- --------JAMES 30 SMITH 20 ADAMS 20 MARTIN 30 WARD 30 MILLER 10 ALLEN 30 ... 14 rows selected.
Selfjoins
EMP (WORKER)
EMPNO ----7839 7698 7782 7566 7654 7499 ENAME -----KING BLAKE CLARK JONES MARTIN ALLEN MGR ---7839 7839 7839 7698 7698
EMP (MANAGER)
EMPNO ENAME ----- -------7839 7839 7839 7698 7698 KING KING KING BLAKE BLAKE
WHO_WORKS_FOR_WHOM ------------------------------BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE ... 13 rows selected.
MAX(SAL) --------5000
AVG AVG COUNT COUNT MAX MAX MIN MIN SUM SUM
SQL> SELECT MIN(sal) AS "Lowest Salary", 2 MAX(sal) AS "Highest Salary" 3 FROM emp; Lowest Salary Highest Salary ------------- -------------800 5000
AVG(COMM) --------550
AVG(NVL(COMM,0)) ---------------157.14286
SQL> 2 3 4 5
AVG(NVL(COMM,0)) ---------------220
2916.6667
SQL> SELECT deptno, COUNT(*) AS "Dept Employees" 2 FROM emp 3 GROUP BY deptno;
Intersect
A B A B
Minus
Copyright 2004, Oracle. All rights reserved.
TITLE TITLE 1400 1400 ----------------300 300 OPERATOR OPERATOR 0 0 MANAGER MANAGER CLERK CLERK
DATE_OUT DATE_OUT --------- ---------------- -------27-NOV-81 27-NOV-81 17-JAN-81 17-JAN-81 22-FEB-80 22-FEB-80
500 500 ANALYST 05-MAY-81 ANALYST 05-MAY-81 ANALYST ANALYST 10-JUN-81 10-JUN-81
UNION A B
ENAME EMPNO ---------- --------ADAMS 7876 ALLEN 7499 BALFORD 6235 ... 20 rows selected.
Copyright 2004, Oracle. All rights reserved.
ENAME JOB SAL ---------- --------- --------ADAMS CLERK 1100 ALLEN SALESMAN 0 ALLEN SALESMAN 1600 BALFORD CLERK 0 ... 23 rows selected.
Copyright 2004, Oracle. All rights reserved.
UNION ALL A B
ENAME EMPNO ---------- --------KING 7839 BLAKE 7698 CLARK 7782 CLARK 7782 ... 23 rows selected.
Copyright 2004, Oracle. All rights reserved.
INTERSECT A B
ENAME EMPNO JOB ENAME EMPNO JOB ---------- --------- ------------------ --------- --------ALLEN 7499 SALESMAN ALLEN 7499 SALESMAN CLARK 7782 MANAGER CLARK 7782 MANAGER SCOTT 7788 ANALYST SCOTT 7788 ANALYST
Copyright 2004, Oracle. All rights reserved.
MINUS A B
MINUS
Display the names, employee numbers, and Display the names, employee numbers, and job titles for all employees who have left the job titles for all employees who have left the company. company.
SQL> 2 3 4 5 SELECT FROM MINUS SELECT FROM name, empid, title emp_history ename, empno, job emp; TITLE TITLE ----------------CLERK CLERK PAY CLERK PAY CLERK
NAME EMPID NAME EMPID ---------- ------------------ --------BALFORD 6235 BALFORD 6235 BRIGGS 7225 BRIGGS 7225 ... ... 6 rows selected. 6 rows selected.
Copyright 2004, Oracle. All rights reserved.
The expressions in the SELECT lists must match in The expressions in the SELECT lists must match in number and datatype. number and datatype. Duplicate rows are automatically eliminated except in Duplicate rows are automatically eliminated except in UNION ALL. UNION ALL. Column names from the first query appear in the result. Column names from the first query appear in the result. The output is sorted in ascending order by default The output is sorted in ascending order by default except in UNION ALL. except in UNION ALL. Parentheses can be used to alter the sequence of Parentheses can be used to alter the sequence of execution. execution.
My dream My dream ------------------------------------------------I'd like to teach I'd like to teach the world to the world to sing sing
Copyright 2004, Oracle. All rights reserved.
Writing Subqueries
Subqueries
SELECT FROM WHERE select_list table expr operator (SELECT FROM
select_list table);
The subquery (inner query) executes once before the main The subquery (inner query) executes once before the main query. query. The result of the subquery is used by the main query (outer The result of the subquery is used by the main query (outer query). query).
Using a Subquery
Who has a salary greater than Jones?
SQL> SELECT ename 2 FROM emp 2975 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE ename='JONES');
Enclose subqueries in parentheses. Enclose subqueries in parentheses. Place subqueries on the right side of the comparison Place subqueries on the right side of the comparison operator. operator. Do not add an ORDER BY clause to a subquery. Do not add an ORDER BY clause to a subquery. Use single-row operators with single-row subqueries. Use single-row operators with single-row subqueries.
Types of Subqueries
Subquery
CLERK
CLERK MANAGER
Single-Row Subqueries
Return only one row Return only one row Use single-row comparison operators Use single-row comparison operators
Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
AND
ow -r le g in S
ry ue bq su
more than
no rows selected
ry ue bq Su
ns ur et r
Multiple-Row Subqueries
Return more than one row Return more than one row Use the IN multiple-row comparison operator to Use the IN multiple-row comparison operator to compare an expression to any member in the list that a compare an expression to any member in the list that a subquery returns subquery returns
ENAME SAL DEPTNO ---------- --------- --------SMITH 800 20 JAMES 950 30 MILLER 1300 10
Controlling Transactions
A DML statement is executed when you: A DML statement is executed when you:
Add new rows to a table (INSERT) Add new rows to a table (INSERT) Modify existing rows in a table (UPDATE) Modify existing rows in a table (UPDATE) Remove existing rows from a table (DELETE) Remove existing rows from a table (DELETE)
A transaction consists of a collection of DML statements A transaction consists of a collection of DML statements that form a logical unit of work. that form a logical unit of work.
Database Transactions
Database transactions can consist of: Database transactions can consist of:
DML statements that make up one consistent change to the DML statements that make up one consistent change to the data data
Example: UPDATE Example: UPDATE
Database Transactions
Begin when the first executable SQL statement is Begin when the first executable SQL statement is executed executed End with one of the following events: End with one of the following events:
COMMIT or ROLLBACK COMMIT or ROLLBACK DDL or DCL statement executes (automatic commit) DDL or DCL statement executes (automatic commit) User exits User exits System crashes System crashes
COMMIT and ROLLBACK ensure data consistency. COMMIT and ROLLBACK ensure data consistency. Users can preview data changes before making Users can preview data changes before making changes permanent. changes permanent. Users can group logically related operations. Users can group logically related operations.
Controlling Transactions
Transaction Transaction
INSERT
COMMIT
UPDATE
INSERT
DELETE
Savepoint A
Savepoint B
ROLLBACK to Savepoint B
ROLLBACK to Savepoint A
ROLLBACK
Copyright 2004, Oracle. All rights reserved.
An automatic commit occurs under the following An automatic commit occurs under the following circumstances: circumstances:
A DDL statement is issued, such as CREATE A DDL statement is issued, such as CREATE A DCL statement is issued, such as GRANT A DCL statement is issued, such as GRANT A normal exit from SQL*Plus occurs without an explicitly A normal exit from SQL*Plus occurs without an explicitly issued COMMIT or ROLLBACK statement issued COMMIT or ROLLBACK statement
An automatic rollback occurs under an abnormal An automatic rollback occurs under an abnormal termination of SQL*Plus or a system failure. termination of SQL*Plus or a system failure.
The previous state of the data can be recovered. The previous state of the data can be recovered. The current user can review the results of the DML operations The current user can review the results of the DML operations by using the SELECT statement. by using the SELECT statement. Other users cannot view the results of the DML statements by Other users cannot view the results of the DML statements by the current user. the current user. The affected rows are locked; other users cannot change the The affected rows are locked; other users cannot change the data within the affected rows. data within the affected rows.
Committing Data
Change the department number of an employee Change the department number of an employee (Clark) identified by a employee number. (Clark) identified by a employee number.
SQL> UPDATE emp SQL> UPDATE emp 2 SET deptno = 10 2 SET deptno = 10 3 WHERE empno = 7782; 3 WHERE empno = 7782; 1 row updated. 1 row updated.
Data changes are undone. Data changes are undone. The previous state of the data is restored. The previous state of the data is restored. Locks on the affected rows are released. Locks on the affected rows are released.
SQL> DELETE FROM employee; 14 rows deleted. SQL> ROLLBACK; Rollback complete.
Copyright 2004, Oracle. All rights reserved.
Create a marker within a current transaction by using Create a marker within a current transaction by using the SAVEPOINT statement. the SAVEPOINT statement. Roll back to that marker by using the ROLLBACK TO Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement. SAVEPOINT statement.
SQL> UPDATE... SQL> SAVEPOINT update_done; Savepoint created. SQL> INSERT... SQL> ROLLBACK TO update_done; Rollback complete.
Statement-Level Rollback
If a single DML statement fails during execution, only If a single DML statement fails during execution, only that statement is rolled back. that statement is rolled back. Oracle implements an implicit savepoint. Oracle implements an implicit savepoint. All other changes are retained. All other changes are retained. The user should terminate transactions explicitly by The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK statement. executing a COMMIT or ROLLBACK statement.
Read Consistency
Read consistency guarantees a consistent view of the Read consistency guarantees a consistent view of the data at all times. data at all times. Changes made by one user do not conflict with Changes made by one user do not conflict with changes made by another user. changes made by another user. Read consistency ensures that on the same data: Read consistency ensures that on the same data:
Readers do not wait for writers or other readers Readers do not wait for writers or other readers Writers do not wait for readers Writers do not wait for readers
User A
SELECT * FROM emp;
User B
Copyright 2004, Oracle. All rights reserved.
Locking
The Oracle Server locks: The Oracle Server locks:
Prevent destructive interaction between concurrent Prevent destructive interaction between concurrent transactions transactions Require no user action Require no user action Automatically use the lowest level of restrictiveness Automatically use the lowest level of restrictiveness Are held for the duration of the transaction Are held for the duration of the transaction Have two basic modes: Have two basic modes:
Exclusive Exclusive Share Share
Locking Modes
Lock Mode Exclusive lock Description Prevents a resource from being shared. The first transaction to lock a resource exclusively is the only transaction that can alter the resource until the exclusive lock is released. Share Allows the resource to be shared. Multiple users reading data can share the data, holding share locks to prevent concurrent access by a writer (who needs an exclusive lock). Several transactions can acquire share locks on the same resource.
Copyright 2004, Oracle. All rights reserved.
Implicit Locking
User Action SELECT ... FROM table ... INSERT INTO table ... UPDATE table ... DELETE FROM table ... DDL Operation Row-Level Lock Table-Level Lock None X X X None None RX RX RX X
Explicit Locking
User Action SELECT FOR UPDATE LOCK TABLE IN option Row-Level lock X None Table-Level lock RS [NOWAIT] Depends on the MODE restrictiveness used
Override the default lock mechanism: Override the default lock mechanism:
For a consistent view of data when reading across For a consistent view of data when reading across multiple tables multiple tables When a transaction may change data based on other When a transaction may change data based on other data that must not change until the whole transaction is data that must not change until the whole transaction is complete complete
Overview of PL/SQL
About PL/SQL
PL/SQL is an extension to SQL with design features of PL/SQL is an extension to SQL with design features of programming languages. programming languages. Data manipulation and query statements of SQL are Data manipulation and query statements of SQL are included within procedural units of code. included within procedural units of code.
PL/SQL Environment
PL/SQL engine PL/SQL block PL/SQL block PL/SQL SQL Procedural Statement Executor
Benefits of PL/SQL
Integration Integration
Application
Shared library
Oracle Server
Benefits of PL/SQL
Improve Performance Improve Performance
SQL
Application Application
Application Application
Benefits of PL/SQL
Modularize program development Modularize program development
DECLARE
BEGIN
EXCEPTION
END;
Benefits of PL/SQL
It is portable. It is portable. You can declare identifiers. You can declare identifiers.
Benefits of PL/SQL
You can program with procedural language control You can program with procedural language control structures. structures. It can handle errors. It can handle errors.
Declaring Variables
Variables, cursors, user-defined exceptions Variables, cursors, user-defined exceptions SQL statements SQL statements PL/SQL statements PL/SQL statements Actions to perform when Actions to perform when
errors occur errors occur
Block Types
Anonymous
[DECLARE] [DECLARE]
Procedure
PROCEDURE name PROCEDURE name IS IS BEGIN BEGIN --statements --statements [EXCEPTION] [EXCEPTION] END; END;
Function
FUNCTION name FUNCTION name RETURN datatype RETURN datatype IS IS BEGIN BEGIN --statements --statements RETURN value; RETURN value; [EXCEPTION] [EXCEPTION] END; END;
Program Constructs
Anonymous Anonymous block block Stored Stored procedure/ procedure/ function function Application Application procedure/ procedure/ function function
END;
Use of Variables
Use variables for: Use variables for:
Temporary storage of data Temporary storage of data Manipulation of stored values Manipulation of stored values Reusability Reusability Ease of maintenance Ease of maintenance
Declare and initialize variables in the declaration Declare and initialize variables in the declaration section. section. Assign new values to variables in the executable Assign new values to variables in the executable section. section. Pass values into PL/SQL blocks through parameters. Pass values into PL/SQL blocks through parameters. View results through output variables. View results through output variables.
Types of Variables
Non-PL/SQL variables: Bind and host variables Non-PL/SQL variables: Bind and host variables
Types of Variables
Non-PL/SQL variables: Bind and host variables Non-PL/SQL variables: Bind and host variables
Types of Variables
TRUE
25-OCT-99
Four score and seven years ago our fathers brought forth upon this continent, a new nation, conceived in LIBERTY, and dedicated
256120.08
Atlanta
Copyright 2004, Oracle. All rights reserved.
Examples Examples
Declare Declare v_hiredate v_hiredate v_deptno v_deptno v_location v_location c_comm c_comm DATE; DATE; NUMBER(2) NOT NULL := 10; NUMBER(2) NOT NULL := 10; VARCHAR2(13) := 'Atlanta'; VARCHAR2(13) := 'Atlanta'; CONSTANT NUMBER := 1400; CONSTANT NUMBER := 1400;
Follow naming conventions. Follow naming conventions. Initialize variables designated as NOT NULL. Initialize variables designated as NOT NULL. Initialize identifiers by using the assignment operator Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word. (:=) or the DEFAULT reserved word. Declare at most one identifier per line. Declare at most one identifier per line.
Naming Rules
Two variables can have the same name, provided they Two variables can have the same name, provided they are in different blocks. are in different blocks. The variable name (identifier) should not be the same The variable name (identifier) should not be the same as the name of table columns used in the block. as the name of table columns used in the block.
ffor or n ttiion n o ven nve s:: co n er g c o tiiffiier s o ng n DECLARE DECLARE miin den t mpn o na m L iide _e mpn empno NUMBER(4); a na Q L empno NUMBER(4); ptt a //S Q lle,, v _e BEGIN BEGIN do p PL S mp e v A do PL a mp SELECT empno A SELECT empno ex a r ex INTO empno INTO empno ffo r o FROM emp
FROM WHERE WHERE END; END; emp ename = 'SMITH'; ename = 'SMITH';
Example Example Set a predefined hiredate for new Set a predefined hiredate for new employees. employees.
v_hiredate := '31-DEC-98'; v_hiredate := '31-DEC-98';
Set the employee name to Maduro. Set the employee name to Maduro.
v_ename := 'Maduro'; v_ename := 'Maduro';
Assignment operator (:=) Assignment operator (:=) DEFAULT keyword DEFAULT keyword NOT NULL constraint NOT NULL constraint
Scalar Datatypes
Hold a single value Hold a single value Have no internal components Have no internal components
TRUE
256120.08
Copyright 2004, Oracle. All rights reserved.
LIBERTY, and dedicated to the proposition that all men are created equal.
Atlanta
VARCHAR2 (maximum_length) VARCHAR2 (maximum_length) NUMBER [(precision, scale)] NUMBER [(precision, scale)] DATE DATE CHAR [(maximum_length)] CHAR [(maximum_length)] LONG LONG LONG RAW LONG RAW BOOLEAN BOOLEAN BINARY_INTEGER BINARY_INTEGER PLS_INTEGER PLS_INTEGER
DATE DATE TIMESTAMP TIMESTAMP TIMESTAMP WITH TIMEZHONE TIMESTAMP WITH TIMEZHONE TIMESTAMP WITH LOCAL TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE INTERVAL YEAR TO MONTH INTERVAL YEAR TO MONTH INVERTAL YEAR TO SECOND INVERTAL YEAR TO SECOND
... ... v_ename v_ename v_balance v_balance v_min_balance v_min_balance ... ...
Only the values TRUE, FALSE, and NULL can be Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable. assigned to a Boolean variable. The variables are connected by the logical operators The variables are connected by the logical operators AND, OR, and NOT. AND, OR, and NOT. The variables always yield TRUE, FALSE, or NULL. The variables always yield TRUE, FALSE, or NULL. Arithmetic, character, and date expressions can be Arithmetic, character, and date expressions can be used to return a Boolean value. used to return a Boolean value.
Composite Datatypes
Bind Variables
Store the annual salary into a SQL*Plus host Store the annual salary into a SQL*Plus host variable. variable.
:g_monthly_sal := v_sal / 12; :g_monthly_sal := v_sal / 12;
Reference non-PL/SQL variables as host variables. Reference non-PL/SQL variables as host variables. Prefix the references with a colon (:). Prefix the references with a colon (:).
DBMS_OUTPUT.PUT_LINE
An Oracle-supplied packaged procedure An Oracle-supplied packaged procedure An alternative for displaying data from a PL/SQL block An alternative for displaying data from a PL/SQL block Must be enabled in SQL*Plus with Must be enabled in SQL*Plus with SET SERVEROUTPUT ON SET SERVEROUTPUT ON
Statements can continue over several lines. Statements can continue over several lines. Lexical units can be separated by: Lexical units can be separated by:
Spaces Spaces Delimiters Delimiters Identifiers Identifiers Literals Literals Comments Comments
Can contain up to 30 characters Can contain up to 30 characters Cannot contain reserved words unless enclosed in Cannot contain reserved words unless enclosed in double quotation marks double quotation marks Must begin with an alphabetic character Must begin with an alphabetic character Should not have the same name as a database table Should not have the same name as a database table column name column name
Character and date literals must be enclosed in single Character and date literals must be enclosed in single quotation marks. quotation marks.
v_ename := 'Henderson'; values or scientific notation. Numbers can be simple Numbers can be simple v_ename := 'Henderson'; values or scientific notation.
Commenting Code
Prefix single-line comments with two dashes (--). Prefix single-line comments with two dashes (--). Place multi-line comments between the symbols /* and Place multi-line comments between the symbols /* and */. */.
Example Example
... ... v_sal NUMBER (9,2); v_sal NUMBER (9,2); BEGIN BEGIN /* Compute the annual salary based on the /* Compute the annual salary based on the monthly salary input from the user */ monthly salary input from the user */ v_sal := &p_monthly_sal * 12; v_sal := &p_monthly_sal * 12; END; -- This is the end of the transaction END; -- This is the end of the transaction
Available: Available:
Single-row number Single-row number Single-row character Single-row character Datatype conversion Datatype conversion Date Date
Same as in SQL
PL/SQL Functions
Example Example
Build the mailing list for a company. Build the mailing list for a company.
Convert the employee name to lowercase. Convert the employee name to lowercase.
v_ename v_ename
:= LOWER(v_ename); := LOWER(v_ename);
Datatype Conversion
Convert data to comparable datatypes. Convert data to comparable datatypes. Mixed datatypes can result in an error and affect Mixed datatypes can result in an error and affect performance. performance. Conversion functions: Conversion functions:
TO_CHAR TO_CHAR TO_DATE TO_DATE TO_NUMBER TO_NUMBER DECLARE DECLARE v_date v_date BEGIN BEGIN SELECT SELECT
VARCHAR2(15); VARCHAR2(15);
TO_CHAR(hiredate, TO_CHAR(hiredate, 'MON. DD, YYYY') 'MON. DD, YYYY') INTO v_date INTO v_date FROM emp FROM emp WHERE empno = 7839; WHERE empno = 7839; END; END;
Copyright 2004, Oracle. All rights reserved.
Datatype Conversion
This statement produces a compilation This statement produces a compilation error if the variable v_date is declared as error if the variable v_date is declared as datatype DATE. datatype DATE.
v_date := 'January 13, 1998'; v_date := 'January 13, 1998';
To correct the error, use the TO_DATE To correct the error, use the TO_DATE conversion function. conversion function.
v_date := TO_DATE ('January 13, 1998', v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY'); 'Month DD, YYYY');
Statements can be nested wherever an executable Statements can be nested wherever an executable statement is allowed. statement is allowed. A nested block becomes a statement. A nested block becomes a statement. An exception section can contain nested blocks. An exception section can contain nested blocks. The scope of an object is the region of the program that The scope of an object is the region of the program that can refer to the object. can refer to the object.
A block can look up to the enclosing block. A block can look up to the enclosing block. A block cannot look down to enclosed blocks. A block cannot look down to enclosed blocks.
Scope of x
Scope of y
Operators in PL/SQL
Logical Logical Arithmetic Arithmetic Concatenation Concatenation Parentheses to control order of Parentheses to control order of operations operations Exponential operator (**) Exponential operator (**)
Same as in SQL
Operators in PL/SQL
Example Example
Increment the index for a loop. Increment the index for a loop.
:= v_count + 1; := v_count + 1;
v_count v_count
Set the value of a Boolean flag. Set the value of a Boolean flag.
v_equal := (v_n1 = v_n2); v_equal := (v_n1 = v_n2); Validate an employee number if it contains a value. Validate an employee number if it contains a value.
v_valid v_valid
Programming Guidelines
Make code maintenance easier by: Make code maintenance easier by:
Documenting code with comments Documenting code with comments Developing a case convention for the code Developing a case convention for the code Developing naming conventions for identifiers and Developing naming conventions for identifiers and other objects other objects Enhancing readability by indenting Enhancing readability by indenting
The names of local variables and formal parameters The names of local variables and formal parameters take precedence over the names of database tables. take precedence over the names of database tables. The names of columns take precedence over the The names of columns take precedence over the names of local variables. names of local variables.
Indenting Code
For clarity, indent each level of code. For clarity, indent each level of code. Example Example
BEGIN BEGIN IF x=0 THEN IF x=0 THEN y:=1; y:=1; END IF; END IF; END; END; DECLARE DECLARE v_deptno NUMBER(2); v_deptno NUMBER(2); v_location VARCHAR2(13); v_location VARCHAR2(13); BEGIN BEGIN SELECT deptno, SELECT deptno, loc loc INTO v_deptno, INTO v_deptno, v_location v_location FROM dept FROM dept WHERE dname = 'SALES'; WHERE dname = 'SALES'; ... ... END; END;
DECLARE DECLARE V_SAL NUMBER(7,2) := 50000; V_SAL NUMBER(7,2) := 50000; V_COMM NUMBER(7,2) := 0; V_COMM NUMBER(7,2) := 0; V_TOTAL_COMP NUMBER(7,2) := V_SAL + V_COMM; V_TOTAL_COMP NUMBER(7,2) := V_SAL + V_COMM; BEGIN ... BEGIN ... V_MESSAGE := 'CLERK not'||V_MESSAGE; V_MESSAGE := 'CLERK not'||V_MESSAGE; END; END; V_MESSAGE := 'SALESMAN'||V_MESSAGE; V_MESSAGE := 'SALESMAN'||V_MESSAGE; END; END;
Copyright 2004, Oracle. All rights reserved.
IF Statements
Syntax Syntax
IF condition THEN IF condition THEN statements; statements; [ELSIF condition THEN [ELSIF condition THEN statements;] statements;] [ELSE [ELSE statements;] statements;] END IF; END IF;
Simple IF statement: Simple IF statement: Set the manager ID to 22 if the employee Set the manager ID to 22 if the employee name is Osborne. name is Osborne.
IF v_ename IF v_ename v_mgr := v_mgr := END IF; END IF; = 'OSBORNE' THEN = 'OSBORNE' THEN 22; 22;
Simple IF Statements
Set the job title to Salesman, the department number to 35, Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last and the commission to 20% of the current salary if the last name is Miller. name is Miller. Example Example
. . . . . . IF v_ename = 'MILLER' THEN IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_job := 'SALESMAN'; v_deptno := 35; v_deptno := 35; v_new_comm := sal * 0.20; v_new_comm := sal * 0.20; END IF; END IF; . . . . . .
THEN actions THEN actions (including further IFs) (including further IFs)
ELSE actions ELSE actions (including further IFs) (including further IFs)
IF-THEN-ELSE Statements
Set a flag for orders where there are fewer than Set a flag for orders where there are fewer than five days between order date and ship date. five days between order date and ship date. Example Example
... ... IF v_shipdate IF v_shipdate v_ship_flag v_ship_flag ELSE ELSE v_ship_flag v_ship_flag END IF; END IF; ... ...
- v_orderdate < 5 THEN - v_orderdate < 5 THEN := 'Acceptable'; := 'Acceptable'; := 'Unacceptable'; := 'Unacceptable';
IF-THEN-ELSIF Statements
For a given value, calculate a percentage of that For a given value, calculate a percentage of that value based on a condition. value based on a condition. Example Example
. . . . . . IF v_start > 100 THEN IF v_start > 100 THEN v_start := 2 * v_start; v_start := 2 * v_start; ELSIF v_start >= 50 THEN ELSIF v_start >= 50 THEN v_start := .5 * v_start; v_start := .5 * v_start; ELSE ELSE v_start := .1 * v_start; v_start := .1 * v_start; END IF; END IF; . . . . . .
You can handle null values with the IS NULL operator. You can handle null values with the IS NULL operator. Any arithmetic expression containing a null value Any arithmetic expression containing a null value evaluates to NULL. evaluates to NULL. Concatenated expressions with null values treat null Concatenated expressions with null values treat null values as an empty string. values as an empty string.
Logic Tables
Build a simple Boolean condition with a Build a simple Boolean condition with a comparison operator. comparison operator.
AND TRUE FALSE NULL OR TRUE FALSE NULL NOT
TRUE
TRUE
FALSE
NULL
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE
FALSE
TRUE
NULL
NULL
FALSE
NULL
NULL
TRUE
NULL
NULL
NULL
NULL
Boolean Conditions
What is the value of V_FLAG in each case? What is the value of V_FLAG in each case?
v_flag := v_reorder_flag AND v_available_flag; v_flag := v_reorder_flag AND v_available_flag;
Loops repeat a statement or sequence of statements Loops repeat a statement or sequence of statements multiple times. multiple times. There are three loop types: There are three loop types:
Basic loop Basic loop FOR loop FOR loop WHILE loop WHILE loop
Basic Loop
Syntax Syntax
LOOP LOOP statement1; statement1; . . . . . . EXIT [WHEN condition]; EXIT [WHEN condition]; END LOOP; END LOOP; -- delimiter -- statements -- EXIT statement -- delimiter
where: where:
condition condition
is a Boolean variable or is a Boolean variable or expression (TRUE, FALSE, expression (TRUE, FALSE, or NULL); or NULL);
Basic Loop
Example Example
DECLARE DECLARE v_ordid item.ordid%TYPE := 601; v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1; v_counter NUMBER(2) := 1; BEGIN BEGIN LOOP LOOP INSERT INTO item(ordid, itemid) INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); VALUES(v_ordid, v_counter); v_counter := v_counter + 1; v_counter := v_counter + 1; EXIT WHEN v_counter > 10; EXIT WHEN v_counter > 10; END LOOP; END LOOP; END; END;
FOR Loop
FOR counter in [REVERSE] FOR counter in [REVERSE] lower_bound..upper_bound LOOP lower_bound..upper_bound LOOP Syntax Syntax statement1; statement1; statement2; statement2; . . . . . . END LOOP; END LOOP;
Use a FOR loop to shortcut the test for the number of Use a FOR loop to shortcut the test for the number of iterations. iterations. Do not declare the index; it is declared implicitly. Do not declare the index; it is declared implicitly.
FOR Loop
Guidelines Guidelines
Reference the counter within the loop only; it is undefined Reference the counter within the loop only; it is undefined outside the loop. outside the loop. Use an expression to reference the existing value of a Use an expression to reference the existing value of a counter. counter. Do not reference the counter as the target of an Do not reference the counter as the target of an assignment. assignment.
FOR Loop
Insert the first 10 new line items for order number Insert the first 10 new line items for order number 601. 601. Example Example
DECLARE DECLARE v_ordid item.ordid%TYPE := 601; v_ordid item.ordid%TYPE := 601; BEGIN BEGIN FOR i IN 1..10 LOOP FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); VALUES(v_ordid, i); END LOOP; END LOOP; END; END;
WHILE Loop
Syntax Syntax
WHILE condition LOOP WHILE condition LOOP statement1; statement1; statement2; statement2; . . . . . . END LOOP; END LOOP; Condition is evaluated at the beginning of each iteration.
Use the WHILE loop to repeat statements while a Use the WHILE loop to repeat statements while a condition is TRUE. condition is TRUE.
WHILE Loop
Example Example
ACCEPT p_new_order PROMPT 'Enter the order number: ACCEPT p_new_order PROMPT 'Enter the order number: ACCEPT p_items ACCEPT p_items PROMPT 'Enter the number of items in this order: PROMPT 'Enter the number of items in this order: DECLARE DECLARE v_count NUMBER(2) := 1; v_count NUMBER(2) := 1; BEGIN BEGIN WHILE v_count <= &p_items LOOP WHILE v_count <= &p_items LOOP INSERT INTO item (ordid, itemid) INSERT INTO item (ordid, itemid) VALUES (&p_new_order, v_count); VALUES (&p_new_order, v_count); v_count := v_count + 1; v_count := v_count + 1; END LOOP; END LOOP; COMMIT; COMMIT; END; END; / / ' ' ' '
Nest loops to multiple levels. Nest loops to multiple levels. Use labels to distinguish between blocks and loops. Use labels to distinguish between blocks and loops. Exit the outer loop with the EXIT statement referencing Exit the outer loop with the EXIT statement referencing the label. the label.
About Cursors
Every SQL statement executed by the Oracle Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Server has an individual cursor associated with it:
Implicit cursors: Declared for all DML and PL/SQL Implicit cursors: Declared for all DML and PL/SQL SELECT statements SELECT statements Explicit cursors: Declared and named by the Explicit cursors: Declared and named by the programmer programmer
Active set 7369 SMITH 7566 JONES Cursor 7788 SCOTT 7876 ADAMS 7902 FORD CLERK MANAGER ANALYST CLERK ANALYST Current row
Create a
named SQL area
Identify
the active set
Load the
current row into variables
Test for
existing rows
Release
the active set
Return to
FETCH if rows found
Cursor
Copyright 2004, Oracle. All rights reserved.
Do not include the INTO clause in the cursor declaration. Do not include the INTO clause in the cursor declaration. If processing rows in a specific sequence is required, use the If processing rows in a specific sequence is required, use the ORDER BY clause in the query. ORDER BY clause in the query.
Open the cursor to execute the query and identify the Open the cursor to execute the query and identify the active set. active set. If the query returns no rows, no exception is raised. If the query returns no rows, no exception is raised. Use cursor attributes to test the outcome after a fetch. Use cursor attributes to test the outcome after a fetch.
Retrieve the current row values into output variables. Retrieve the current row values into output variables. Include the same number of variables. Include the same number of variables. Match each variable to correspond to the columns Match each variable to correspond to the columns positionally. positionally. Test to see if the cursor contains rows. Test to see if the cursor contains rows.
FETCH emp_cursor INTO v_empno, v_ename; FETCH emp_cursor INTO v_empno, v_ename; ... ... OPEN defined_cursor; OPEN defined_cursor; LOOP LOOP FETCH defined_cursor INTO defined_variables FETCH defined_cursor INTO defined_variables EXIT WHEN ...; EXIT WHEN ...; ... ... -- Process the retrieved data -- Process the retrieved data ... ... END; END;
cursor_name; cursor_name;
Close the cursor after completing the processing of the Close the cursor after completing the processing of the rows. rows. Reopen the cursor, if required. Reopen the cursor, if required. Do not attempt to fetch data from a cursor once it has Do not attempt to fetch data from a cursor once it has been closed. been closed.
%ROWCOUNT
Number
Fetch rows only when the cursor is open. Fetch rows only when the cursor is open. Use the %ISOPEN cursor attribute before performing a Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. fetch to test whether the cursor is open.
Example Example
IF NOT emp_cursor%ISOPEN THEN IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; OPEN emp_cursor; END IF; END IF; LOOP LOOP FETCH emp_cursor... FETCH emp_cursor...
Process several rows from an explicit cursor using a Process several rows from an explicit cursor using a loop. loop. Fetch a row with each iteration. Fetch a row with each iteration. Use the %NOTFOUND attribute to write a test for an Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. unsuccessful fetch. Use explicit cursor attributes to test the success of Use explicit cursor attributes to test the success of each fetch. each fetch.
Use the %ROWCOUNT cursor attribute to retrieve an Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. exact number of rows. Use the %NOTFOUND cursor attribute to determine Use the %NOTFOUND cursor attribute to determine when to exit the loop. when to exit the loop.
DECLARE DECLARE CURSOR emp_cursor IS CURSOR emp_cursor IS SELECT empno, ename SELECT empno, ename FROM emp; FROM emp; emp_record emp_record emp_cursor%ROWTYPE; emp_cursor%ROWTYPE; BEGIN BEGIN OPEN emp_cursor; OPEN emp_cursor; LOOP LOOP FETCH emp_cursor INTO emp_record; FETCH emp_cursor INTO emp_record; ... ...
cursors. cursors. Implicit open, fetch, and close occur. Implicit open, fetch, and close occur. The record is implicitly declared. The record is implicitly declared.
BEGIN BEGIN FOR emp_record IN ( SELECT ename, deptno FOR emp_record IN ( SELECT ename, deptno FROM emp) LOOP FROM emp) LOOP -- implicit open and implicit fetch occur -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN IF emp_record.deptno = 30 THEN ... ... END LOOP; -- implicit close occurs END LOOP; -- implicit close occurs END; END;
Pass parameter values to a cursor when the cursor is opened and the query is executed. Open an explicit cursor several times with a different active set each time.
Explicit locking lets you deny access for the duration of Explicit locking lets you deny access for the duration of a transaction. a transaction. Lock the rows before the update or delete. Lock the rows before the update or delete.
DECLARE DECLARE CURSOR emp_cursor IS CURSOR emp_cursor IS SELECT empno, ename, sal SELECT empno, ename, sal FROM FROM emp emp WHERE deptno = 30 WHERE deptno = 30 FOR UPDATE NOWAIT; FOR UPDATE NOWAIT;
Use cursors to update or delete the current row. Include the FOR UPDATE clause in the cursor query to lock the rows first. Use the WHERE CURRENT OF clause to reference the current row from an explicit cursor.
Handling Exceptions
Handling Exceptions
Trap the exception DECLARE BEGIN
Exception is raised
EXCEPTION
Exception Types
Predefined Oracle Server Predefined Oracle Server Non-predefined Oracle Server Non-predefined Oracle Server User-defined User-defined
Implicitly raised
Explicitly raised
Trapping Exceptions
Syntax Syntax
EXCEPTION EXCEPTION WHEN exception1 [OR exception2 . . .] THEN WHEN exception1 [OR exception2 . . .] THEN statement1; statement1; statement2; statement2; . . . . . . [WHEN exception3 [OR exception4 . . .] THEN [WHEN exception3 [OR exception4 . . .] THEN statement1; statement1; statement2; statement2; . . .] . . .] [WHEN OTHERS THEN [WHEN OTHERS THEN statement1; statement1; statement2; statement2; . . .] . . .]
WHEN OTHERS is the last clause. WHEN OTHERS is the last clause. EXCEPTION keyword starts exception-handling EXCEPTION keyword starts exception-handling section. section. Several exception handlers are allowed. Several exception handlers are allowed. Only one handler is processed before leaving the Only one handler is processed before leaving the block. block.
Reference the standard name in the exceptionReference the standard name in the exceptionhandling routine. handling routine. Sample predefined exceptions: Sample predefined exceptions:
NO_DATA_FOUND NO_DATA_FOUND TOO_MANY_ROWS TOO_MANY_ROWS INVALID_CURSOR INVALID_CURSOR ZERO_DIVIDE ZERO_DIVIDE DUP_VAL_ON_INDEX DUP_VAL_ON_INDEX
Predefined Exception
Syntax Syntax
BEGIN SELECT ... COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN statement1; statement2; WHEN TOO_MANY_ROWS THEN statement1; WHEN OTHERS THEN statement1; statement2; statement3; END;
Declare
Associate
Reference
Exception-handling section
Declarative section
Name the
exception
Non-Predefined Error
Trap for Oracle Server error number Trap for Oracle Server error number 2292, an integrity constraint violation. 2292, an integrity constraint violation.
DECLARE DECLARE e_emps_remaining EXCEPTION; EXCEPTION; e_emps_remaining EXCEPTION; e_emps_remaining PRAGMA EXCEPTION_INIT ( PRAGMA EXCEPTION_INIT ( PRAGMA EXCEPTION_INIT ( e_emps_remaining, -2292); e_emps_remaining, -2292); e_emps_remaining, -2292); v_deptno dept.deptno%TYPE := &p_deptno; v_deptno dept.deptno%TYPE := &p_deptno; BEGIN BEGIN DELETE FROM dept DELETE FROM dept WHERE deptno = v_deptno; WHERE deptno = v_deptno; COMMIT; COMMIT; EXCEPTION EXCEPTION WHEN e_emps_remaining THEN WHEN e_emps_remaining THEN DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(v_deptno) || '. Employees exist. '); TO_CHAR(v_deptno) || '. Employees exist. '); END; END;
Copyright 2004, Oracle. All rights reserved.
1 2
Declare
Declarative section
Raise
Executable section
Reference
Exception-handling section
Name the
exception
Explicitly raise
the exception by using the RAISE statement
Handle the
raised exception
User-Defined Exception
Example Example
DECLARE DECLARE EXCEPTION; e_invalid_product EXCEPTION; e_invalid_product EXCEPTION; BEGIN BEGIN UPDATE product UPDATE product SET descrip = '&product_description' SET descrip = '&product_description' WHERE prodid = &product_number; WHERE prodid = &product_number; IF SQL%NOTFOUND THEN IF SQL%NOTFOUND THEN RAISE e_invalid_product; RAISE e_invalid_product; END IF; END IF; COMMIT; COMMIT; EXCEPTION EXCEPTION e_invalid_product WHEN e_invalid_product THEN WHEN e_invalid_product THEN DBMS_OUTPUT.PUT_LINE('Invalid product number.'); DBMS_OUTPUT.PUT_LINE('Invalid product number.'); END; END; 1
SQLCODE SQLCODE
Returns the numeric value for the error code Returns the numeric value for the error code
SQLERRM SQLERRM
Returns the message associated with the error number Returns the message associated with the error number
SQLCODE ; := SQLERRM ;
Calling Environments
SQL*Plus Procedure Builder Oracle Developer Forms Precompiler application An enclosing PL/SQL block
Copyright 2004, Oracle. All rights reserved.
Displays error number and message to screen Displays error number and message to screen Accesses error number and message in a trigger by means of the ERROR_CODE and ERROR_TEXT packaged functions Accesses exception number through the SQLCA data structure Traps exception in exceptionhandling routine of enclosing block
RAISE_APPLICATION_ERROR Procedure
Syntax Syntax
raise_application_error (error_number, raise_application_error (error_number, message[, {TRUE | FALSE}]); message[, {TRUE | FALSE}]);
A procedure that lets you issue user-defined error A procedure that lets you issue user-defined error messages from stored subprograms messages from stored subprograms Called only from an executing stored subprogram Called only from an executing stored subprogram
RAISE_APPLICATION_ERROR Procedure
Returns error conditions to the user in a manner Returns error conditions to the user in a manner consistent with other Oracle Server errors consistent with other Oracle Server errors
Package
Trigger
Managing Dependencies
Q U E S T I O N S A N S W E R S