SlideShare una empresa de Scribd logo
1 de 365
Introduction
Lesson Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object]
Retrieving Data Using  the SQL  SELECT  Statement
Objectives ,[object Object],[object Object],[object Object],[object Object]
Capabilities of SQL  SELECT  Statements Selection Projection Table 1 Table 2 Table 1 Table 1 Join
Basic  SELECT  Statement ,[object Object],[object Object],SELECT *|{[DISTINCT]  column | expression  [ alias ],...} FROM  table;
Selecting All Columns SELECT * FROM  departments;
Selecting Specific Columns SELECT department_id, location_id FROM  departments;
Writing SQL Statements ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Column Heading Defaults ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Arithmetic Expressions ,[object Object],Multiply * Divide ,[object Object],Subtract ,[object Object],Add ,[object Object],Description Operator
Using Arithmetic Operators SELECT last_name, salary, salary + 300 FROM  employees; …
Operator Precedence SELECT last_name, salary, 12*salary+100 FROM  employees; SELECT last_name, salary, 12*(salary+100)‏ FROM  employees; 1 2 … …
Defining a Null Value ,[object Object],[object Object],SELECT last_name, job_id, salary, commission_pct FROM  employees; … …
Null Values  in Arithmetic Expressions ,[object Object],SELECT last_name, 12*salary*commission_pct FROM  employees; … …
Defining a Column Alias ,[object Object],[object Object],[object Object],[object Object],[object Object]
Using Column Aliases SELECT last_name "Name" , salary*12 "Annual Salary" FROM  employees; SELECT last_name AS name, commission_pct comm FROM  employees; … …
Concatenation Operator ,[object Object],[object Object],[object Object],[object Object],SELECT last_name||job_id AS "Employees" FROM  employees; …
Literal Character Strings ,[object Object],[object Object],[object Object]
Using Literal Character Strings … SELECT last_name ||' is a '||job_id  AS "Employee Details" FROM  employees;
Alternative Quote ( q ) Operator ,[object Object],[object Object],[object Object],SELECT department_name ||  q'[, it's assigned Manager Id: ]'  || manager_id  AS "Department and Manager"  FROM departments; …
Duplicate Rows ,[object Object],SELECT department_id FROM  employees; SELECT DISTINCT department_id FROM  employees; … 1 2 …
Displaying Table Structure ,[object Object],DESC[RIBE]  tablename
Displaying Table Structure DESCRIBE employees
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],SELECT *|{[DISTINCT]  column|expression  [ alias ],...} FROM  table;
Restricting and Sorting Data
Objectives ,[object Object],[object Object],[object Object],[object Object]
Limiting Rows Using a Selection “ retrieve all employees in department 90” EMPLOYEES …
Limiting the Rows That Are Selected ,[object Object],[object Object],SELECT *|{[DISTINCT]  column|expression  [ alias ],...} FROM  table [WHERE  condition(s) ];
Using the  WHERE  Clause SELECT employee_id, last_name, job_id, department_id FROM  employees WHERE  department_id = 90 ;
Character Strings and Dates ,[object Object],[object Object],[object Object],SELECT last_name, job_id, department_id FROM  employees WHERE  last_name = 'Whalen' ;
Comparison Conditions Not equal to ,[object Object],Between two values (inclusive)‏ BETWEEN ...AND... Match any of a list of values  IN(set)‏ Match a character pattern  LIKE Is a null value  IS NULL Less than ,[object Object],Less than or equal to ,[object Object],Greater than or equal to >= Greater than ,[object Object],Equal to ,[object Object],Meaning Operator
Using Comparison Conditions SELECT last_name, salary FROM  employees WHERE  salary <= 3000 ;
Using the  BETWEEN  Condition ,[object Object],SELECT last_name, salary FROM  employees WHERE  salary BETWEEN 2500 AND 3500 ; Lower limit Upper limit
Using the  IN  Condition ,[object Object],SELECT employee_id, last_name, salary, manager_id FROM  employees WHERE  manager_id IN (100, 101, 201) ;
Using the  LIKE  Condition ,[object Object],[object Object],[object Object],[object Object],SELECT first_name FROM  employees WHERE first_name LIKE 'S%' ;
[object Object],[object Object],Using the  LIKE  Condition SELECT last_name FROM  employees WHERE  last_name LIKE '_o%' ;
Using the  NULL  Conditions ,[object Object],SELECT last_name, manager_id FROM  employees WHERE  manager_id IS NULL ;
Logical Conditions Returns  TRUE  if the following condition is false NOT Returns  TRUE  if  either  component condition is true ,[object Object],Returns  TRUE  if  both  component conditions are true ,[object Object],Meaning Operator
Using the  AND  Operator SELECT employee_id, last_name, job_id, salary FROM  employees WHERE  salary >=10000 AND  job_id LIKE '%MAN%' ; AND  requires both conditions to be true:
Using the  OR  Operator SELECT employee_id, last_name, job_id, salary FROM  employees WHERE  salary >= 10000 OR  job_id LIKE '%MAN%' ; ,[object Object]
Using the  NOT  Operator SELECT last_name, job_id FROM  employees WHERE  job_id  NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
Rules of Precedence You can use parentheses to override rules of precedence. Not equal to ,[object Object],NOT  logical condition ,[object Object],AND  logical condition ,[object Object],OR  logical condition ,[object Object],IS   [NOT]   NULL ,  LIKE ,  [NOT]   IN ,[object Object],[NOT] BETWEEN ,[object Object],Comparison conditions ,[object Object],Concatenation operator ,[object Object],Arithmetic operators ,[object Object],Meaning Operator
Rules of Precedence SELECT last_name, job_id, salary FROM  employees WHERE  job_id = 'SA_REP' OR  job_id = 'AD_PRES' AND  salary > 15000; SELECT last_name, job_id, salary FROM  employees WHERE  ( job_id = 'SA_REP' OR  job_id = 'AD_PRES' )‏ AND  salary > 15000; 1 2
Using the  ORDER BY  Clause ,[object Object],[object Object],[object Object],[object Object],SELECT  last_name, job_id, department_id, hire_date FROM  employees ORDER BY hire_date ; …
Sorting ,[object Object],[object Object],[object Object],SELECT  last_name, job_id, department_id, hire_date FROM  employees ORDER BY hire_date DESC ; 1 SELECT employee_id, last_name, salary*12 annsal FROM  employees ORDER BY annsal ; 2 SELECT last_name, department_id, salary FROM  employees ORDER BY department_id, salary DESC; 3
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],SELECT  *|{[DISTINCT]  column|expression  [ alias ],...} FROM  table [WHERE  condition(s) ] [ORDER BY { column, expr, alias } [ASC|DESC]] ;
Displaying Data  from Multiple Tables
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object]
Obtaining Data from Multiple Tables EMPLOYEES   DEPARTMENTS  … …
Types of Joins ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Joining Tables Using SQL:1999 Syntax ,[object Object],SELECT table1.column, table2.column FROM table1 [NATURAL JOIN  table2 ] | [JOIN  table2  USING ( column_name )] | [JOIN  table2   ON ( table1.column_name  =  table2.column_name )]| [LEFT|RIGHT|FULL OUTER JOIN  table2   ON ( table1.column_name  =  table2.column_name )]| [CROSS JOIN  table2 ];
Creating Natural Joins ,[object Object],[object Object],[object Object]
Retrieving Records with Natural Joins SELECT department_id, department_name, location_id, city FROM  departments NATURAL JOIN locations ;
Creating Joins with the  USING  Clause ,[object Object],[object Object],[object Object],[object Object]
Joining Column Names EMPLOYEES   DEPARTMENTS  Foreign key Primary key … …
Retrieving Records with the  USING  Clause SELECT employees.employee_id, employees.last_name,  departments.location_id, department_id FROM  employees JOIN departments USING (department_id) ; …
Qualifying Ambiguous  Column Names ,[object Object],[object Object],[object Object],[object Object]
Using Table Aliases ,[object Object],[object Object],SELECT e.employee_id, e.last_name,  d.location_id, department_id FROM  employees e JOIN departments d USING (department_id) ;
Creating Joins with the  ON  Clause ,[object Object],[object Object],[object Object],[object Object]
Retrieving Records with the  ON  Clause SELECT e.employee_id, e.last_name, e.department_id,  d.department_id, d.location_id FROM  employees e JOIN departments d ON  (e.department_id = d.department_id); …
Self-Joins Using the  ON  Clause MANAGER_ID  in the  WORKER  table is equal to  EMPLOYEE_ID  in the  MANAGER  table. EMPLOYEES (WORKER) EMPLOYEES (MANAGER) … …
Self-Joins Using the  ON  Clause SELECT e.last_name emp, m.last_name mgr FROM  employees e JOIN employees m ON  (e.manager_id = m.employee_id); …
Applying Additional Conditions to a Join SELECT e.employee_id, e.last_name, e.department_id,  d.department_id, d.location_id FROM  employees e JOIN departments d ON  (e.department_id = d.department_id) AND  e.manager_id = 149 ;
Creating Three-Way Joins with the  ON  Clause SELECT employee_id, city, department_name FROM  employees e  JOIN  departments d ON  d.department_id = e.department_id  JOIN  locations l ON  d.location_id = l.location_id; …
Nonequijoins EMPLOYEES JOB_GRADES Salary in the  EMPLOYEES   table must be between  lowest salary and highest  salary in the  JOB_GRADES table. …
Retrieving Records  with Nonequijoins SELECT e.last_name, e.salary, j.grade_level FROM  employees e JOIN job_grades j ON  e.salary  BETWEEN j.lowest_sal AND j.highest_sal; …
Outer Joins EMPLOYEES DEPARTMENTS There are no employees in department 190.  …
INNER  Versus  OUTER  Joins ,[object Object],[object Object],[object Object]
LEFT OUTER JOIN SELECT e.last_name, e.department_id, d.department_name FROM  employees e LEFT OUTER JOIN departments d ON  (e.department_id = d.department_id) ; …
RIGHT OUTER JOIN SELECT e.last_name, e.department_id, d.department_name FROM  employees e RIGHT OUTER JOIN departments d ON  (e.department_id = d.department_id) ; …
FULL OUTER JOIN SELECT e.last_name, d.department_id, d.department_name FROM  employees e FULL OUTER JOIN departments d ON  (e.department_id = d.department_id) ; …
Cartesian Products ,[object Object],[object Object],[object Object],[object Object],[object Object]
Generating a Cartesian Product Cartesian product:  20 x 8 = 160 rows EMPLOYEES   (20 rows) DEPARTMENTS   (8 rows) … …
Creating   Cross   Joins ,[object Object],[object Object],SELECT last_name, department_name FROM  employees CROSS JOIN departments ; …
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Manipulating Data
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Data Manipulation Language ,[object Object],[object Object],[object Object],[object Object],[object Object]
Adding a New Row to a Table DEPARTMENTS  New  row Insert new row into the DEPARTMENTS   table
INSERT  Statement Syntax ,[object Object],[object Object],INSERT INTO table  [( column  [ , column... ])] VALUES (value  [ , value... ]);
Inserting New Rows ,[object Object],[object Object],[object Object],[object Object],INSERT INTO departments(department_id,  department_name, manager_id, location_id) VALUES (70, 'Public Relations', 100, 1700); 1 row created.
Inserting Rows with Null Values ,[object Object],INSERT INTO departments VALUES (100, 'Finance', NULL, NULL); 1 row created. INSERT INTO departments (department_id,  department_name  ) VALUES (30, 'Purchasing'); 1 row created. ,[object Object]
Inserting Special Values ,[object Object],INSERT INTO employees (employee_id,  first_name, last_name,  email, phone_number, hire_date, job_id, salary,  commission_pct, manager_id, department_id) VALUES   (113,  'Louis', 'Popp',  'LPOPP', '515.124.4567',  SYSDATE, 'AC_ACCOUNT', 6900,  NULL, 205, 100); 1 row created.
[object Object],[object Object],Inserting Specific Date Values INSERT INTO employees VALUES  (114,  'Den', 'Raphealy',  'DRAPHEAL', '515.127.4561', TO_DATE('FEB 3, 1999', 'MON DD, YYYY'), 'AC_ACCOUNT', 11000, NULL, 100, 30); 1 row created.
Copying Rows  from Another Table ,[object Object],[object Object],[object Object],INSERT INTO sales_reps(id, name, salary, commission_pct) SELECT employee_id, last_name, salary, commission_pct FROM  employees WHERE  job_id LIKE '%REP%'; 4 rows created.
Changing Data in a Table EMPLOYEES Update rows in the  EMPLOYEES  table:
[object Object],[object Object],UPDATE  Statement Syntax UPDATE table SET column  =  value  [,  column  =  value, ... ] [WHERE  condition ];
[object Object],[object Object],Updating Rows in a Table UPDATE employees SET  department_id = 70 WHERE  employee_id = 113; 1 row updated. UPDATE  copy_emp SET  department_id = 110; 22 rows updated.
Removing a Row from a Table  Delete a row from the  DEPARTMENTS  table: DEPARTMENTS
DELETE  Statement ,[object Object],DELETE [FROM]   table [WHERE   condition ];
Deleting Rows from a Table ,[object Object],[object Object],DELETE FROM departments WHERE  department_name = 'Finance'; 1 row deleted. DELETE FROM  copy_emp; 22 rows deleted.
Database Transactions ,[object Object],[object Object],[object Object],[object Object]
Database Transactions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Advantages of  COMMIT   and  ROLLBACK  Statements ,[object Object],[object Object],[object Object],[object Object]
Controlling Transactions SAVEPOINT   B SAVEPOINT   A DELETE INSERT UPDATE INSERT COMMIT Time Transaction ROLLBACK  to SAVEPOINT B ROLLBACK  to SAVEPOINT A ROLLBACK
Rolling Back Changes to a Marker ,[object Object],[object Object],UPDATE... SAVEPOINT update_done; Savepoint created. INSERT... ROLLBACK TO update_done; Rollback complete.
Implicit Transaction Processing ,[object Object],[object Object],[object Object],[object Object],[object Object]
 
State of the Data  Before  COMMIT  or  ROLLBACK ,[object Object],[object Object],[object Object],[object Object]
State of the Data After  COMMIT ,[object Object],[object Object],[object Object],[object Object],[object Object]
Committing Data ,[object Object],[object Object],COMMIT; Commit complete. DELETE FROM employees WHERE  employee_id = 99999; 1 row deleted. INSERT INTO departments  VALUES (290, 'Corporate Tax', NULL, 1700); 1 row created.
State of the Data After  ROLLBACK ,[object Object],[object Object],[object Object],[object Object],DELETE FROM copy_emp; 20 rows deleted. ROLLBACK ; Rollback complete.
State of the Data After  ROLLBACK DELETE FROM test; 25,000 rows deleted. ROLLBACK; Rollback complete. DELETE FROM test WHERE  id = 100; 1 row deleted. SELECT * FROM  test WHERE  id = 100; No rows selected. COMMIT; Commit complete.
Statement-Level Rollback ,[object Object],[object Object],[object Object],[object Object]
Summary ,[object Object],Adds a new row to the table INSERT Modifies existing rows in the table UPDATE Removes existing rows from the table DELETE Makes all pending changes permanent COMMIT Discards all pending data changes ROLLBACK Is used to roll back to the savepoint marker SAVEPOINT Description Function
Using DDL Statements to Create and Manage Tables
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Database Objects Logically represents subsets of data from one or more tables  View  Generates numeric values Sequence  Basic unit of storage; composed of rows  Table Gives alternative names to objects Synonym  Improves the performance of some queries Index Description Object
Naming Rules ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],CREATE TABLE  Statement CREATE TABLE [ schema .] table ( column   datatype  [DEFAULT  expr ][, ...]);
Referencing Another User’s Tables ,[object Object],[object Object],USERB USERA SELECT *  FROM userB.employees; SELECT *  FROM userA.employees;
[object Object],[object Object],[object Object],[object Object],DEFAULT  Option ... hire_date DATE DEFAULT SYSDATE, ...   CREATE TABLE hire_dates   (id  NUMBER(8), hire_date DATE DEFAULT SYSDATE ); Table created.
Creating Tables ,[object Object],[object Object],DESCRIBE dept CREATE TABLE dept   (deptno  NUMBER(2), dname  VARCHAR2(14), loc  VARCHAR2(13), create_date DATE DEFAULT SYSDATE ); Table created.
Data Types Raw binary data RAW and LONG RAW   Binary data (up to 4 GB) BLOB Binary data stored in an external file (up to 4 GB) BFILE Date and time values DATE  Variable-length character data (up to 2 GB) LONG  Character data (up to 4 GB) CLOB A base-64 number system representing the unique address of a row in its table ROWID Fixed-length character data CHAR( size )  Variable-length numeric data NUMBER( p , s)   Variable-length character data VARCHAR2( size ) Description Data Type
 
Datetime Data Types ,[object Object],Stored as an interval of years and months INTERVAL YEAR TO MONTH Stored as an interval of days, hours, minutes, and seconds INTERVAL DAY TO SECOND Date with fractional seconds TIMESTAMP Description Data Type
Datetime Data Types ,[object Object],[object Object],[object Object],TIMESTAMP[(fractional_seconds_precision)] TIMESTAMP[(fractional_seconds_precision)] WITH TIME ZONE TIMESTAMP[(fractional_seconds_precision)] WITH LOCAL TIME ZONE
 
Datetime Data Types ,[object Object],[object Object],INTERVAL YEAR [(year_precision)] TO MONTH INTERVAL DAY [(day_precision)]  TO SECOND [(fractional_seconds_precision)]
 
INTERVAL DAY TO SECOND  Data Type ,[object Object],INTERVAL '4 5:12:10.222' DAY TO SECOND(3) Indicates 4 days, 5 hours, 12 minutes, 10 seconds,  and 222 thousandths of a second. INTERVAL '4 5:12' DAY TO MINUTE Indicates 4 days, 5 hours and 12 minutes. INTERVAL '400 5' DAY(3) TO HOUR Indicates 400 days 5 hours. INTERVAL '11:12:10.2222222' HOUR TO SECOND(7) indicates 11 hours, 12 minutes, and 10.2222222 seconds.
Including Constraints ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Constraint Guidelines ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],Defining Constraints CREATE TABLE [ schema .] table ( column   datatype  [DEFAULT  expr ] [ column_constraint ], ... [ table_constraint ][,...] ); column,... [CONSTRAINT  constraint_name ]  constraint_type ( column , ...), column   [CONSTRAINT  constraint_name ]  constraint_type ,
Defining Constraints ,[object Object],[object Object],CREATE TABLE employees( employee_id  NUMBER(6) CONSTRAINT emp_emp_id_pk PRIMARY KEY, first_name  VARCHAR2(20), ...); CREATE TABLE employees( employee_id  NUMBER(6), first_name  VARCHAR2(20), ... job_id  VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk  PRIMARY KEY (EMPLOYEE_ID) ); 1 2
NOT NULL  Constraint ,[object Object],NOT NULL  constraint (No row can contain a null value for this column.) Absence of  NOT NULL  constraint  (Any row can contain a null value for this column.) NOT NULL   constraint …
UNIQUE  Constraint EMPLOYEES  UNIQUE  constraint INSERT INTO Not allowed: already exists Allowed …
UNIQUE  Constraint ,[object Object],CREATE TABLE employees( employee_id  NUMBER(6), last_name  VARCHAR2(25) NOT NULL, email  VARCHAR2(25), salary  NUMBER(8,2), commission_pct  NUMBER(2,2), hire_date  DATE NOT NULL, ...  CONSTRAINT emp_email_uk UNIQUE(email));
PRIMARY KEY  Constraint DEPARTMENTS   PRIMARY KEY INSERT INTO Not allowed (null value) Not allowed  (50 already exists) …
FOREIGN KEY  Constraint DEPARTMENTS   EMPLOYEES FOREIGN KEY INSERT INTO Not allowed (9 does not exist) Allowed PRIMARY KEY … …
FOREIGN KEY  Constraint ,[object Object],CREATE TABLE employees( employee_id  NUMBER(6), last_name  VARCHAR2(25) NOT NULL, email  VARCHAR2(25), salary  NUMBER(8,2), commission_pct  NUMBER(2,2), hire_date  DATE NOT NULL, ... department_id  NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) REFERENCES departments(department_id), CONSTRAINT emp_email_uk UNIQUE(email));
FOREIGN KEY  Constraint: Keywords ,[object Object],[object Object],[object Object],[object Object]
CHECK  Constraint ,[object Object],[object Object],[object Object],[object Object],[object Object],..., salary NUMBER(2) CONSTRAINT emp_salary_min  CHECK (salary > 0),...
CREATE TABLE : Example CREATE TABLE employees ( employee_id  NUMBER(6) CONSTRAINT  emp_employee_id  PRIMARY KEY , first_name  VARCHAR2(20) , last_name  VARCHAR2(25) CONSTRAINT  emp_last_name_nn  NOT NULL , email  VARCHAR2(25) CONSTRAINT  emp_email_nn  NOT NULL CONSTRAINT  emp_email_uk  UNIQUE , phone_number  VARCHAR2(20) , hire_date  DATE CONSTRAINT  emp_hire_date_nn  NOT NULL , job_id  VARCHAR2(10) CONSTRAINT  emp_job_nn  NOT NULL , salary  NUMBER(8,2) CONSTRAINT  emp_salary_ck  CHECK (salary>0) , commission_pct NUMBER(2,2) , manager_id  NUMBER(6) , department_id  NUMBER(4) CONSTRAINT  emp_dept_fk  REFERENCES departments (department_id));
Violating Constraints  ,[object Object],UPDATE employees * ERROR at line 1: ORA-02291: integrity constraint (HR.EMP_DEPT_FK) violated - parent key not found UPDATE employees SET  department_id = 55 WHERE  department_id = 110;
Violating Constraints ,[object Object],DELETE FROM departments WHERE  department_id = 60; DELETE FROM departments * ERROR at line 1: ORA-02292: integrity constraint (HR.EMP_DEPT_FK) violated - child record found
Creating a Table by Using a Subquery ,[object Object],[object Object],[object Object],CREATE TABLE  table   [( column ,  column ...)] AS  subquery;
Creating a Table by Using a Subquery CREATE TABLE  dept80 AS    SELECT  employee_id, last_name,  salary*12 ANNSAL,  hire_date   FROM  employees   WHERE  department_id = 80; Table created. DESCRIBE dept80
ALTER TABLE  Statement ,[object Object],[object Object],[object Object],[object Object],[object Object]
Dropping a Table ,[object Object],[object Object],[object Object],[object Object],[object Object],DROP TABLE dept80; Table dropped.
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Introduction to PL/SQL
Lesson Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What Is PL/SQL? ,[object Object],[object Object],[object Object],[object Object]
About PL/SQL ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
PL/SQL Environment PL/SQL Engine Oracle Database Server SQL Statement  Executor Procedural  Statement  Executor procedural SQL PL/SQL Block
Benefits of PL/SQL SQL IF...THEN SQL ELSE SQL END IF; SQL ,[object Object],[object Object],SQL 1 SQL 2 …
Benefits of PL/SQL ,[object Object],[object Object],[object Object],[object Object]
Benefits of PL/SQL
PL/SQL Block Structure ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
PL/SQL Block Structure
Block Types ,[object Object],[DECLARE] BEGIN --statements [EXCEPTION] END; PROCEDURE name IS BEGIN --statements [EXCEPTION] END; FUNCTION name RETURN datatype IS BEGIN --statements RETURN value; [EXCEPTION] END;
Block Types
Program Constructs Application triggers Application packages Application procedures or functions Anonymous blocks Tools Constructs Object types Database triggers Stored packages Stored procedures or functions Anonymous blocks Database Server Constructs  Object types
Program Constructs
Create an Anonymous Block ,[object Object]
Execute an Anonymous Block ,[object Object],PLQL procedure successfully completed.
Test the Output of a PL/SQL Block ,[object Object],[object Object],[object Object],SET SERVEROUTPUT ON … DBMS_OUTPUT.PUT_LINE( '  The First Name of the Employee is  '  || f_name); …
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Declaring PL/SQL Variables
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Use of Variables ,[object Object],[object Object],[object Object],[object Object],SELECT  first_name,  department_id  INTO  emp_fname, emp_deptno FROM … emp_fname emp_deptno Jennifer 10
Identifiers ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Handling Variables in PL/SQL ,[object Object],[object Object],[object Object],[object Object],[object Object]
Declaring and Initializing PL/SQL Variables Syntax: Examples: identifier  [CONSTANT]  datatype  [NOT NULL]  [:= | DEFAULT  expr ]; DECLARE   emp_hiredate DATE; emp_deptno NUMBER(2) NOT NULL := 10;   location   VARCHAR2(13) := 'Atlanta'; c_comm CONSTANT NUMBER := 1400;
Declaring and Initializing PL/SQL Variables SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20); BEGIN   DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); Myname := 'John'; DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); END; / SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20):= 'John'; BEGIN Myname := 'Steven'; DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); END;  / 1 2
Delimiters in String Literals SET SERVEROUTPUT ON DECLARE event VARCHAR2(15); BEGIN event := q'!Father's day!'; DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is : '||event); event := q'[Mother's day]'; DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is : '||event); END; /
Types of Variables ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Types of Variables TRUE 25-JAN-01 Atlanta 256120.08 The soul of the lazy man   desires, and has nothing;   but the soul of the diligent  shall be made rich.
Guidelines for Declaring and Initializing PL/SQL Variables ,[object Object],[object Object],[object Object],[object Object],[object Object],Myname VARCHAR2(20):='John'; Myname VARCHAR2(20) DEFAULT 'John';
Guidelines for Declaring PL/SQL Variables ,[object Object],DECLARE employee_id NUMBER(6); BEGIN SELECT   employee_id   INTO employee_id   FROM employees WHERE  last_name = 'Kochhar'; END; / ,[object Object]
Scalar Data Types ,[object Object],[object Object],Atlanta TRUE 25-JAN-01 256120.08 The soul of the lazy man   desires, and has nothing;   but the soul of the diligent  shall be made rich.
Base Scalar Data Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
 
Base Scalar Data Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
 
BINARY_FLOAT  and  BINARY_DOUBLE ,[object Object],[object Object],[object Object],[object Object]
BINARY_FLOAT  and  BINARY_DOUBLE
Declaring Scalar Variables  ,[object Object],DECLARE emp_job VARCHAR2(9); count_loop   BINARY_INTEGER := 0; dept_total_sal NUMBER(9,2) := 0; orderdate   DATE := SYSDATE + 7; c_tax_rate CONSTANT NUMBER(3,2) := 8.25; valid   BOOLEAN NOT NULL := TRUE; ...
The  %TYPE  Attribute ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The  %TYPE  Attribute
Declaring Variables  with the  %TYPE  Attribute ,[object Object],[object Object],... emp_lname  employees.last_name%TYPE; balance  NUMBER(7,2);   min_balance  balance%TYPE := 1000; ... identifier table.column_name%TYPE;
Declaring Boolean Variables ,[object Object],[object Object],[object Object],[object Object]
Bind Variables ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
 
Printing Bind Variables ,[object Object],VARIABLE emp_salary NUMBER BEGIN SELECT salary  INTO :emp_salary  FROM  employees WHERE employee_id = 178;  END; / PRINT emp_salary SELECT first_name, last_name FROM employees  WHERE salary=:emp_salary;
Printing Bind Variables ,[object Object],VARIABLE emp_salary NUMBER SET AUTOPRINT ON BEGIN SELECT salary  INTO :emp_salary  FROM  employees WHERE employee_id = 178;  END; /
Substitution Variables ,[object Object],[object Object],[object Object],VARIABLE emp_salary NUMBER SET AUTOPRINT ON DECLARE   empno NUMBER(6):=&empno; BEGIN   SELECT salary  INTO :emp_salary    FROM  employees WHERE employee_id = empno;  END; /
Substitution Variables 1 2 3
Prompt for Substitution Variables SET VERIFY OFF VARIABLE emp_salary NUMBER ACCEPT empno PROMPT 'Please enter a valid employee number: '   SET AUTOPRINT ON DECLARE   empno NUMBER(6):= &empno; BEGIN   SELECT salary  INTO :emp_salary  FROM  employees   WHERE employee_id = empno; END; /
Using  DEFINE  for User Variable ,[object Object],SET VERIFY OFF DEFINE lname= Urman DECLARE fname VARCHAR2(25); BEGIN SELECT first_name INTO fname FROM employees  WHERE last_name='&lname'; END; /
Composite Data Types  TRUE  23-DEC-98 ATLANTA  1 5000  2 2345  3 12  4 3456 1 SMITH  2 JONES  3 NANCY  4 TIM PL/SQL table structure PL/SQL table structure PLS_INTEGER   VARCHAR2 PLS_INTEGER  NUMBER
LOB  Data Type Variables Book ( CLOB ) Photo ( BLOB ) Movie ( BFILE ) NCLOB
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Interacting with the Oracle Server
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
SQL Statements in PL/SQL ,[object Object],[object Object],[object Object]
SQL Statements in PL/SQL
SELECT  Statements in PL/SQL ,[object Object],[object Object],SELECT  select_list INTO  { variable_name [,  variable_name ] ...   |  record_name }   FROM   table [WHERE   condition ];
 
SELECT  Statements in PL/SQL ,[object Object],[object Object],[object Object],SET SERVEROUTPUT ON DECLARE fname VARCHAR2(25); BEGIN SELECT first_name INTO fname  FROM employees WHERE employee_id=200; DBMS_OUTPUT.PUT_LINE(' First Name is : '||fname); END; /
SELECT  Statements in PL/SQL
Retrieving Data in PL/SQL ,[object Object],[object Object],DECLARE emp_hiredate  employees.hire_date%TYPE; emp_salary  employees.salary%TYPE;  BEGIN SELECT  hire_date, salary INTO  emp_hiredate, emp_salary FROM  employees WHERE  employee_id = 100;  END; /
Retrieving Data in PL/SQL ,[object Object],[object Object],SET SERVEROUTPUT ON DECLARE  sum_sal  NUMBER(10,2);  deptno  NUMBER NOT NULL := 60;  BEGIN SELECT  SUM(salary)  -- group function INTO sum_sal FROM employees WHERE  department_id = deptno; DBMS_OUTPUT.PUT_LINE ('The sum of salary is '   || sum_sal); END; /
Naming Conventions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Naming Conventions ,[object Object],[object Object],[object Object],[object Object],[object Object]
Manipulating Data Using PL/SQL ,[object Object],[object Object],[object Object],[object Object],[object Object],INSERT UPDATE DELETE MERGE
Inserting Data ,[object Object],[object Object],BEGIN INSERT INTO employees (employee_id, first_name, last_name, email,  hire_date, job_id, salary) VALUES(employees_seq.NEXTVAL, 'Ruth', 'Cores', 'RCORES',sysdate, 'AD_ASST', 4000); END; /
Updating Data ,[object Object],[object Object],DECLARE sal_increase  employees.salary%TYPE := 800;  BEGIN UPDATE employees SET salary = salary + sal_increase WHERE job_id = 'ST_CLERK'; END; /
Deleting Data ,[object Object],[object Object],DECLARE deptno  employees.department_id%TYPE := 10;  BEGIN DELETE FROM  employees WHERE  department_id = deptno; END; /
Merging Rows ,[object Object],DECLARE empno employees.employee_id%TYPE := 100; BEGIN MERGE INTO copy_emp c USING employees e ON (e.employee_id = empno) WHEN MATCHED THEN UPDATE SET c.first_name  = e.first_name, c.last_name  = e.last_name, c.email  = e.email, . . . WHEN NOT MATCHED THEN INSERT VALUES(e.employee_id, e.first_name, e.last_name, . . .,e.department_id); END; /
 
SQL Cursor ,[object Object],[object Object],[object Object],[object Object]
 
SQL Cursor Attributes for Implicit Cursors ,[object Object],Boolean attribute that evaluates to  TRUE  if  the most recent SQL statement did not return even one row. SQL%NOTFOUND Boolean attribute that evaluates to  TRUE  if the most recent SQL statement returned at least one row. SQL%FOUND An integer value that represents number of rows affected by the most recent SQL statement.  SQL%ROWCOUNT
SQL Cursor Attributes for Implicit Cursors ,[object Object],[object Object],VARIABLE rows_deleted VARCHAR2(30) DECLARE empno employees.employee_id%TYPE := 176; BEGIN DELETE FROM  employees  WHERE employee_id = empno; :rows_deleted := (SQL%ROWCOUNT || ' row deleted.'); END; / PRINT rows_deleted
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object]
Writing Control Structures
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Controlling Flow of Execution for loop while
IF  Statements ,[object Object],IF  condition  THEN statements ; [ELSIF  condition  THEN  statements ;] [ELSE  statements ;] END IF;
IF  Statements
Simple  IF  Statement DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child ');  END IF; END; /
IF   THEN   ELSE  Statement SET SERVEROUTPUT ON DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child ');  ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; /
IF ELSIF ELSE  Clause DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSIF myage < 20  THEN  DBMS_OUTPUT.PUT_LINE(' I am young '); ELSIF myage < 30 THEN DBMS_OUTPUT.PUT_LINE(' I am in my twenties'); ELSIF myage < 40 THEN DBMS_OUTPUT.PUT_LINE(' I am in my thirties'); ELSE DBMS_OUTPUT.PUT_LINE(' I am always young '); END IF; END; /
NULL  Values   in  IF  Statements DECLARE myage number; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child ');  ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; /
CASE  Expressions ,[object Object],[object Object],CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 ... WHEN expressionN THEN resultN [ELSE resultN+1] END; /
CASE  Expressions: Example SET SERVEROUTPUT ON SET VERIFY OFF DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal :=  CASE grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| grade || '    Appraisal ' || appraisal); END; /
Searched  CASE  Expressions DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal :=  CASE  WHEN grade = 'A' THEN 'Excellent' WHEN grade IN ('B','C') THEN 'Good'  ELSE 'No such grade'  END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| grade || '    Appraisal ' || appraisal); END; /
CASE  Statement DECLARE deptid NUMBER; deptname VARCHAR2(20); emps NUMBER; mngid NUMBER:= 108;  BEGIN CASE  mngid WHEN  108 THEN  SELECT department_id, department_name    INTO deptid, deptname FROM departments    WHERE manager_id=108; SELECT count(*) INTO emps FROM employees    WHERE department_id=deptid; WHEN  200 THEN  ... END CASE; DBMS_OUTPUT.PUT_LINE ('You are working in the '|| deptname|| ' department. There are '||emps ||' employees in this  department'); END; /
Handling Nulls ,[object Object],[object Object],[object Object],[object Object]
Logic Tables ,[object Object],AND TRUE FALSE NULL TRUE FALSE NULL TRUE NULL NULL NULL FALSE FALSE FALSE FALSE FALSE NOT TRUE FALSE NULL FALSE TRUE NULL TRUE NULL OR TRUE FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSE NULL NULL NULL FALSE
Boolean Conditions ,[object Object],REORDER_FLAG AVAILABLE_FLAG FLAG TRUE    TRUE TRUE  FALSE NULL  TRUE NULL  FALSE flag := reorder_flag AND available_flag;  ? ? ? ?
Iterative Control:  LOOP  Statements ,[object Object],[object Object],[object Object],[object Object],[object Object]
Basic Loops ,[object Object],LOOP  statement1 ; . . . EXIT [WHEN  condition ]; END LOOP;
Basic Loops ,[object Object],DECLARE countryid  locations.country_id%TYPE := 'CA'; loc_id  locations.location_id%TYPE; counter   NUMBER(2) := 1; new_city  locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id)   INTO loc_id FROM locations WHERE country_id = countryid; LOOP INSERT INTO locations(location_id, city, country_id)  VALUES((loc_id + counter), new_city, countryid); counter := counter + 1; EXIT WHEN counter > 3; END LOOP; END; /
WHILE  Loops ,[object Object],[object Object],WHILE  condition  LOOP statement1; statement2; . . . END LOOP;
WHILE  Loops ,[object Object],DECLARE countryid  locations.country_id%TYPE := 'CA'; loc_id  locations.location_id%TYPE; new_city  locations.city%TYPE := 'Montreal'; counter  NUMBER := 1; BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid; WHILE counter <= 3 LOOP INSERT INTO locations(location_id, city, country_id)  VALUES((loc_id + counter), new_city, countryid); counter := counter + 1; END LOOP; END; /
FOR  Loops ,[object Object],[object Object],[object Object],FOR  counter  IN [REVERSE]  lower_bound..upper_bound  LOOP  statement1; statement2; . . . END LOOP;
FOR  Loops
FOR  Loops ,[object Object],DECLARE countryid  locations.country_id%TYPE := 'CA'; loc_id  locations.location_id%TYPE; new_city  locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id) INTO loc_id  FROM locations WHERE country_id = countryid; FOR i IN 1..3 LOOP INSERT INTO locations(location_id, city, country_id)  VALUES((loc_id + i), new_city, countryid ); END LOOP; END; /
FOR  Loops ,[object Object],[object Object],[object Object],[object Object]
Guidelines While Using Loops ,[object Object],[object Object],[object Object]
Nested Loops and Labels ,[object Object],[object Object],[object Object]
Nested Loops and Labels ... BEGIN <<Outer_loop>>   LOOP counter := counter+1; EXIT WHEN counter>10; <<Inner_loop>>   LOOP ... EXIT Outer_loop WHEN total_done = 'YES'; -- Leave both loops EXIT WHEN  inner_ done = 'YES'; -- Leave inner loop only ... END LOOP  Inner_loop ; ... END LOOP  Outer_loop ; END;  /
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Working with Composite  Data Types
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Composite Data Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Composite Data Types ,[object Object],[object Object]
PL/SQL Records ,[object Object],[object Object],[object Object],[object Object],[object Object]
Creating a PL/SQL Record ,[object Object],TYPE  type_name  IS RECORD ( field_declaration[, field_declaration]…); field_name {field_type  |  variable%TYPE  |  table.column%TYPE  |  table%ROWTYPE} [[NOT NULL] {:= | DEFAULT}  expr ]   identifier type_name;   1 2 field_declaration :
Creating a PL/SQL Record ,[object Object],[object Object],... TYPE emp_record_type IS RECORD (last_name  VARCHAR2(25), job_id  VARCHAR2(10), salary  NUMBER(8,2)); emp_record  emp_record_type; ...
PL/SQL Record Structure Example: 100  King  AD_PRES employee_id  number(6) last_name  varchar2(25) job_id  varchar2(10) Field2 (data type) Field3 (data type) Field1 (data type) Field2 (data type) Field3 (data type) Field1 (data type)
The  %ROWTYPE  Attribute ,[object Object],[object Object],[object Object],DECLARE   identifier  reference%ROWTYPE; Syntax:
The  %ROWTYPE  Attribute ,[object Object],[object Object],[object Object]
Advantages of Using  %ROWTYPE ,[object Object],[object Object],[object Object]
The  %ROWTYPE  Attribute ... DEFINE employee_number = 124  DECLARE   emp_rec  employees%ROWTYPE;  BEGIN   SELECT * INTO emp_rec FROM employees   WHERE  employee_id = &employee_number;   INSERT INTO retired_emps(empno, ename, job, mgr,   hiredate, leavedate, sal, comm, deptno)   VALUES (emp_rec.employee_id, emp_rec.last_name,   emp_rec.job_id,emp_rec.manager_id,   emp_rec.hire_date, SYSDATE, emp_rec.salary,    emp_rec.commission_pct, emp_rec.department_id); END; /
Inserting a Record Using  %ROWTYPE ... DEFINE employee_number = 124 DECLARE emp_rec  retired_emps%ROWTYPE; BEGIN SELECT employee_id, last_name, job_id, manager_id,   hire_date, hire_date, salary, commission_pct,  department_id INTO emp_rec FROM employees WHERE  employee_id = &employee_number; INSERT INTO retired_emps VALUES emp_rec; END; / SELECT * FROM retired_emps;
Updating a Row in a Table Using a Record SET SERVEROUTPUT ON SET VERIFY OFF DEFINE employee_number = 124 DECLARE emp_rec retired_emps%ROWTYPE; BEGIN SELECT * INTO emp_rec FROM retired_emps; emp_rec.leavedate:=SYSDATE; UPDATE retired_emps SET ROW = emp_rec WHERE  empno=&employee_number; END; / SELECT * FROM retired_emps;
INDEX   BY  Tables or Associative Arrays ,[object Object],[object Object],[object Object],[object Object]
Creating an  INDEX   BY  Table ,[object Object],TYPE  type_name  IS TABLE OF  {column_type | variable%TYPE | table.column%TYPE} [NOT NULL]  | table%ROWTYPE  [INDEX BY PLS_INTEGER | BINARY_INTEGER | VARCHAR2(< size >)]; identifier type_name; ... TYPE ename_table_type   IS TABLE OF  employees.last_name%TYPE INDEX BY PLS_INTEGER;  ...  ename_table ename_table_type; Declare an  INDEX   BY  table to store the last names of employees.
Creating an  INDEX   BY  Table
INDEX   BY  Table Structure Unique Key Value ... ... 1 Jones 5 Smith 3 Maduro ... ... PLS_INTEGER Scalar
Creating an  INDEX   BY  Table ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Using  INDEX   BY  Table Methods ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
INDEX   BY  Table of Records ,[object Object],[object Object],DECLARE TYPE dept_table_type IS TABLE OF  departments%ROWTYPE INDEX BY PLS_INTEGER; dept_table dept_table_type; -- Each element of dept_table is a record
INDEX   BY  Table of Records
Example of  INDEX   BY  Table of Records SET SERVEROUTPUT ON DECLARE TYPE emp_table_type IS TABLE OF employees%ROWTYPE INDEX BY PLS_INTEGER; my_emp_table  emp_table_type; max_count  NUMBER(3):= 104;  BEGIN FOR i IN 100..max_count LOOP SELECT * INTO my_emp_table(i) FROM employees WHERE employee_id = i; END LOOP; FOR i IN my_emp_table.FIRST..my_emp_table.LAST  LOOP DBMS_OUTPUT.PUT_LINE(my_emp_table(i).last_name); END LOOP; END;  /
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Using Explicit Cursors
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
About Cursors ,[object Object],[object Object],[object Object]
Explicit Cursor Operations Active set Table 100 King  AD_PRES 101 Kochhar AD_VP 102 De Haan AD_VP .  .  . .  .  . .  .  . 139 Seo  ST_CLERK 140 Patel  ST_CLERK .  .  .
Controlling Explicit Cursors ,[object Object],FETCH ,[object Object],EMPTY? ,[object Object],No ,[object Object],CLOSE Yes ,[object Object],DECLARE ,[object Object],OPEN
Controlling Explicit Cursors Fetch a row. Close the cursor. Cursor  pointer Open the cursor. 1 2 3 Cursor  pointer Cursor  pointer
Declaring the Cursor ,[object Object],CURSOR  cursor_name  IS select_statement; Examples: DECLARE CURSOR emp_cursor IS  SELECT employee_id, last_name FROM employees   WHERE department_id =30; DECLARE locid NUMBER:= 1700; CURSOR dept_cursor IS SELECT * FROM departments    WHERE location_id = locid; ...
Declaring the Cursor
Opening the Cursor DECLARE CURSOR emp_cursor IS  SELECT employee_id, last_name FROM employees   WHERE department_id =30; ... BEGIN OPEN emp_cursor;
Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS  SELECT employee_id, last_name FROM employees WHERE department_id =30; empno employees.employee_id%TYPE; lname employees.last_name%TYPE; BEGIN OPEN emp_cursor; FETCH emp_cursor INTO empno, lname; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname);    ...  END; /
Fetching Data from the Cursor
Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS  SELECT employee_id, last_name FROM employees WHERE  department_id =30; empno employees.employee_id%TYPE; lname employees.last_name%TYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO empno, lname; EXIT WHEN emp_cursor%NOTFOUND ; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname);  END LOOP;   ... END; /
Closing the Cursor ...  LOOP FETCH emp_cursor INTO empno, lname; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname);  END LOOP; CLOSE emp_cursor; END; /
Cursors and Records ,[object Object],DECLARE  CURSOR emp_cursor IS  SELECT employee_id, last_name FROM employees WHERE  department_id =30; emp_record emp_cursor%ROWTYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO emp_record; ...
Cursor  FOR  Loops ,[object Object],[object Object],[object Object],[object Object],FOR  record_name  IN  cursor_name  LOOP  statement1 ; statement2 ; . . . END LOOP;
Cursor  FOR  Loops SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS  SELECT employee_id, last_name FROM employees WHERE department_id =30;  BEGIN FOR emp_record IN emp_cursor   LOOP DBMS_OUTPUT.PUT_LINE(  emp_record.employee_id     ||' ' || emp_record.last_name );  END LOOP;  END; /
Explicit Cursor Attributes ,[object Object],Boolean Evaluates to  TRUE  if the cursor is open Evaluates to  TRUE  if the most recent fetch does not return a row Evaluates to  TRUE  if the most recent fetch returns a row; complement of  %NOTFOUND Evaluates to the total number of  rows returned so far Boolean Boolean Number %ISOPEN %NOTFOUND %FOUND %ROWCOUNT Attribute     Type    Description
The  %ISOPEN  Attribute ,[object Object],[object Object],[object Object],IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; END IF; LOOP FETCH emp_cursor...
Example of  %ROWCOUNT  and  %NOTFOUND SET SERVEROUTPUT ON DECLARE empno employees.employee_id%TYPE; ename employees.last_name%TYPE; CURSOR emp_cursor IS SELECT employee_id,  last_name FROM employees; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO empno, ename; EXIT WHEN emp_cursor%ROWCOUNT > 10 OR  emp_cursor%NOTFOUND;   DBMS_OUTPUT.PUT_LINE(TO_CHAR(empno)  ||' '|| ename); END LOOP; CLOSE emp_cursor; END ; /
Cursor  FOR  Loops Using Subqueries ,[object Object],[object Object],SET SERVEROUTPUT ON BEGIN FOR emp_record IN (SELECT employee_id, last_name    FROM employees WHERE department_id =30) LOOP DBMS_OUTPUT.PUT_LINE( emp_record.employee_id ||'  '||emp_record.last_name);  END LOOP;  END; /
Cursors with Parameters ,[object Object],[object Object],[object Object],CURSOR  cursor_name   [( parameter_name datatype , ...)] IS select_statement ; OPEN cursor_name(parameter_value ,.....) ;
Cursors with Parameters SET SERVEROUTPUT ON DECLARE CURSOR  emp_cursor (deptno NUMBER) IS SELECT  employee_id, last_name FROM  employees WHERE  department_id = deptno; dept_id NUMBER; lname  VARCHAR2(15); BEGIN OPEN emp_cursor (10); ... CLOSE emp_cursor; OPEN emp_cursor (20); ...
The  FOR   UPDATE  Clause ,[object Object],[object Object],[object Object],SELECT ...  FROM ... FOR UPDATE [OF  column_reference ][NOWAIT | WAIT  n ];
The  FOR   UPDATE  Clause
The  WHERE   CURRENT   OF  Clause ,[object Object],[object Object],[object Object],[object Object],WHERE CURRENT OF  cursor ; UPDATE employees  SET  salary = ...  WHERE CURRENT OF  emp_cursor;
Cursors with Subqueries DECLARE CURSOR my_cursor IS SELECT t1.department_id, t1.department_name,  t2.staff FROM  departments t1, (SELECT department_id, COUNT(*) AS STAFF FROM employees GROUP BY department_id) t2 WHERE t1.department_id = t2.department_id AND  t2.staff >= 3; ... Example:
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Handling Exceptions
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE  first_name='John';  DBMS_OUTPUT.PUT_LINE ('John''s last name is : '   ||lname); END; /
Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE  first_name='John';  DBMS_OUTPUT.PUT_LINE ('John''s last name is : '    ||lname); EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE (' Your select statement    retrieved multiple rows. Consider using a    cursor.'); END; /
Handling Exceptions with PL/SQL ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Handling Exceptions Exception  raised Is the exception  trapped?  yes Execute statements in the  EXCEPTION section Terminate  gracefully no Terminate  abruptly Propagate the  exception
Exception Types ,[object Object],[object Object],[object Object],} Implicitly raised Explicitly raised
Trapping Exceptions ,[object Object],EXCEPTION WHEN  exception1  [OR  exception2  . . .] THEN statement1 ; statement2 ; . . . [WHEN  exception3  [OR  exception4  . . .] THEN statement1 ; statement2 ; . . .] [WHEN OTHERS THEN statement1 ; statement2 ; . . .]
Trapping Exceptions
Guidelines for Trapping Exceptions ,[object Object],[object Object],[object Object],[object Object]
Trapping Predefined Oracle Server Errors ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
 
 
Trapping Non-Predefined Oracle  Server Errors Declarative section Name the exception Code  PRAGMA EXCEPTION_INIT EXCEPTION  section Handle the raised exception Associate Reference Declare
Non-Predefined Error ,[object Object],SET SERVEROUTPUT ON DECLARE insert_excep EXCEPTION; PRAGMA EXCEPTION_INIT   (insert_excep, -01400); BEGIN INSERT INTO departments   (department_id, department_name) VALUES (280, NULL); EXCEPTION WHEN insert_excep THEN DBMS_OUTPUT.PUT_LINE('INSERT OPERATION FAILED'); DBMS_OUTPUT.PUT_LINE(SQLERRM); END; / 1 2 3
Functions for Trapping Exceptions ,[object Object],[object Object]
Functions for Trapping Exceptions ,[object Object],DECLARE error_code  NUMBER; error_message  VARCHAR2(255); BEGIN ... EXCEPTION ... WHEN OTHERS THEN ROLLBACK; error_code := SQLCODE ; error_message := SQLERRM ; INSERT INTO errors (e_user, e_date, error_code, error_message) VALUES(USER,SYSDATE,error_code,  error_message); END; /
Trapping User-Defined Exceptions Declarative section Name the exception. Executable section Explicitly raise the exception by using the  RAISE  statement. Exception -handling section Handle the raised exception. Raise Reference Declare
Trapping User-Defined Exceptions ... ACCEPT deptno PROMPT 'Please enter the department number:' ACCEPT name  PROMPT 'Please enter the department name:' DECLARE invalid_department EXCEPTION; name VARCHAR2(20):='&name'; deptno NUMBER :=&deptno; BEGIN UPDATE  departments SET  department_name = name WHERE  department_id = deptno; IF SQL%NOTFOUND THEN RAISE invalid_department; END IF; COMMIT; EXCEPTION WHEN invalid_department  THEN DBMS_OUTPUT.PUT_LINE('No such department id.'); END; / 1 2 3
Calling Environments Traps exception in exception-handling routine of enclosing block An enclosing PL/SQL block Accesses exception number through the  SQLCA  data structure Precompiler  application Accesses error number and message in an  ON-ERROR  trigger by means of the  ERROR_CODE  and  ERROR_TEXT  packaged functions Oracle Developer Forms Displays error number and message to screen Procedure Builder Displays error number and message to screen i SQL*Plus
Propagating Exceptions in a Subblock DECLARE . . . no_rows exception; integrity exception; PRAGMA EXCEPTION_INIT (integrity, -2292); BEGIN FOR c_record IN emp_cursor LOOP BEGIN SELECT ... UPDATE ... IF SQL%NOTFOUND THEN RAISE no_rows; END IF; END; END LOOP; EXCEPTION WHEN integrity THEN ... WHEN no_rows THEN ... END; / Subblocks can handle an exception or pass the exception to the enclosing block.
The  RAISE_APPLICATION_ERROR Procedure ,[object Object],[object Object],[object Object],raise_application_error ( error_number, message [, {TRUE | FALSE}]);
The  RAISE_APPLICATION_ERROR Procedure ,[object Object],[object Object],[object Object],[object Object]
RAISE_APPLICATION_ERROR ,[object Object],BEGIN ... DELETE FROM employees WHERE  manager_id = v_mgr; IF SQL%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20202, 'This is not a valid manager'); END IF; ... Executable section: ... EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR (-20201, 'Manager is not a valid employee.'); END; /
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Creating Stored Procedures and Functions
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Procedures and Functions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Differences Between Anonymous Blocks and Subprograms Can take parameters Cannot take parameters Subprograms called functions must return values  Do not return values They are named and therefore can be invoked by other applications Cannot be invoked by other applications Stored in the database Not stored in the database Compiled only once Compiled every time Named PL/SQL blocks Unnamed PL/SQL blocks Subprograms Anonymous Blocks
Procedure: Syntax CREATE [OR REPLACE] PROCEDURE  procedure_name [( argument1  [ mode1 ]  datatype1, argument2  [ mode2 ]  datatype2, . . . )] IS|AS procedure_body;
Procedure: Example ... CREATE TABLE dept AS SELECT * FROM departments; CREATE PROCEDURE  add_dept  IS dept_id dept.department_id%TYPE; dept_name dept.department_name%TYPE; BEGIN dept_id:=280; dept_name:= ' ST-Curriculum ' ; INSERT INTO dept(department_id,department_name) VALUES(dept_id,dept_name);  DBMS_OUTPUT.PUT_LINE( '  Inserted  ' ||   SQL%ROWCOUNT || '  row  ' ); END;  /
Procedure: Example
Invoking the Procedure BEGIN add_dept; END; / SELECT department_id, department_name FROM dept WHERE department_id=280;
Function: Syntax C REATE [OR REPLACE] FUNCTION  function_name [( argument1  [ mode1 ]  datatype1, argument2  [ mode2 ]  datatype2, . . . )] RETURN  datatype IS|AS function_body;
Function: Example CREATE FUNCTION  check_sal  RETURN Boolean IS dept_id employees.department_id%TYPE; empno  employees.employee_id%TYPE; sal  employees.salary%TYPE; avg_sal employees.salary%TYPE; BEGIN empno:=205; SELECT salary,department_id INTO sal,dept_id  FROM employees WHERE employee_id= empno; SELECT avg(salary) INTO avg_sal FROM employees  WHERE department_id=dept_id; IF sal > avg_sal THEN RETURN TRUE; ELSE RETURN FALSE;  END IF; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL; END; /
Invoking the Function SET SERVEROUTPUT ON BEGIN IF (check_sal IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned   NULL due to exception'); ELSIF (check_sal) THEN  DBMS_OUTPUT.PUT_LINE('Salary > average'); ELSE DBMS_OUTPUT.PUT_LINE('Salary < average'); END IF; END; /
Passing Parameter to the Function DROP FUNCTION check_sal; / CREATE FUNCTION check_sal (empno employees.employee_id%TYPE)  RETURN Boolean IS dept_id employees.department_id%TYPE; sal  employees.salary%TYPE; avg_sal employees.salary%TYPE; BEGIN SELECT salary,department_id INTO sal,dept_id FROM employees WHERE employee_id=empno; SELECT avg(salary) INTO avg_sal FROM employees  WHERE department_id=dept_id; IF sal > avg_sal THEN RETURN TRUE; ELSE RETURN FALSE;  END IF; EXCEPTION ... ...
Invoking the Function with a Parameter BEGIN DBMS_OUTPUT.PUT_LINE('Checking for employee with id 205'); IF (check_sal(205) IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned   NULL due to exception'); ELSIF (check_sal(205)) THEN  DBMS_OUTPUT.PUT_LINE('Salary > average'); ELSE DBMS_OUTPUT.PUT_LINE('Salary < average'); END IF; DBMS_OUTPUT.PUT_LINE('Checking for employee with id 70'); IF (check_sal(70) IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned   NULL due to exception'); ELSIF (check_sal(70)) THEN  ... END IF; END; /
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Goals of the Course ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt

Más contenido relacionado

La actualidad más candente

Sql intro
Sql introSql intro
Sql introglubox
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Achmad Solichin
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginnersRam Sagar Mourya
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle SqlAhmed Yaseen
 
Retrieving data using the sql select statement
Retrieving data using the sql select statementRetrieving data using the sql select statement
Retrieving data using the sql select statementSyed Zaid Irshad
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schoolsfarhan516
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive dataAmrit Kaur
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize outputSyed Zaid Irshad
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functionsNitesh Singh
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Vidyasagar Mundroy
 

La actualidad más candente (18)

sql language
sql languagesql language
sql language
 
Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
 
Sql intro
Sql introSql intro
Sql intro
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
Lab1 select statement
Lab1 select statementLab1 select statement
Lab1 select statement
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
BIS05 Introduction to SQL
BIS05 Introduction to SQLBIS05 Introduction to SQL
BIS05 Introduction to SQL
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
Sql basics
Sql  basicsSql  basics
Sql basics
 
zekeLabs sql-slides
zekeLabs sql-slideszekeLabs sql-slides
zekeLabs sql-slides
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle Sql
 
Retrieving data using the sql select statement
Retrieving data using the sql select statementRetrieving data using the sql select statement
Retrieving data using the sql select statement
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize output
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
 

Similar a Chinabankppt

Similar a Chinabankppt (20)

SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
 
Les02
Les02Les02
Les02
 
Les02
Les02Les02
Les02
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
Restricting and sorting data
Restricting and sorting dataRestricting and sorting data
Restricting and sorting data
 
Les01
Les01Les01
Les01
 
Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sql
 
e computer notes - Writing basic sql select statements
e computer notes - Writing basic sql select statementse computer notes - Writing basic sql select statements
e computer notes - Writing basic sql select statements
 
Module03
Module03Module03
Module03
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL Statments
 
Les18
Les18Les18
Les18
 
e computer notes - Restricting and sorting data
e computer notes -  Restricting and sorting datae computer notes -  Restricting and sorting data
e computer notes - Restricting and sorting data
 
01 basic orders
01   basic orders01   basic orders
01 basic orders
 
Oracle Baisc Tutorial
Oracle Baisc TutorialOracle Baisc Tutorial
Oracle Baisc Tutorial
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
Oracle - Program with PL/SQL - Lession 03
Oracle - Program with PL/SQL - Lession 03Oracle - Program with PL/SQL - Lession 03
Oracle - Program with PL/SQL - Lession 03
 
Les06
Les06Les06
Les06
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 

Último

Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...HetalPathak10
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Osopher
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPCeline George
 

Último (20)

Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERP
 

Chinabankppt

  • 2.
  • 3. Retrieving Data Using the SQL SELECT Statement
  • 4.
  • 5. Capabilities of SQL SELECT Statements Selection Projection Table 1 Table 2 Table 1 Table 1 Join
  • 6.
  • 7. Selecting All Columns SELECT * FROM departments;
  • 8. Selecting Specific Columns SELECT department_id, location_id FROM departments;
  • 9.
  • 10.
  • 11.
  • 12. Using Arithmetic Operators SELECT last_name, salary, salary + 300 FROM employees; …
  • 13. Operator Precedence SELECT last_name, salary, 12*salary+100 FROM employees; SELECT last_name, salary, 12*(salary+100)‏ FROM employees; 1 2 … …
  • 14.
  • 15.
  • 16.
  • 17. Using Column Aliases SELECT last_name &quot;Name&quot; , salary*12 &quot;Annual Salary&quot; FROM employees; SELECT last_name AS name, commission_pct comm FROM employees; … …
  • 18.
  • 19.
  • 20. Using Literal Character Strings … SELECT last_name ||' is a '||job_id AS &quot;Employee Details&quot; FROM employees;
  • 21.
  • 22.
  • 23.
  • 24. Displaying Table Structure DESCRIBE employees
  • 25.
  • 27.
  • 28. Limiting Rows Using a Selection “ retrieve all employees in department 90” EMPLOYEES …
  • 29.
  • 30. Using the WHERE Clause SELECT employee_id, last_name, job_id, department_id FROM employees WHERE department_id = 90 ;
  • 31.
  • 32.
  • 33. Using Comparison Conditions SELECT last_name, salary FROM employees WHERE salary <= 3000 ;
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40. Using the AND Operator SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >=10000 AND job_id LIKE '%MAN%' ; AND requires both conditions to be true:
  • 41.
  • 42. Using the NOT Operator SELECT last_name, job_id FROM employees WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
  • 43.
  • 44. Rules of Precedence SELECT last_name, job_id, salary FROM employees WHERE job_id = 'SA_REP' OR job_id = 'AD_PRES' AND salary > 15000; SELECT last_name, job_id, salary FROM employees WHERE ( job_id = 'SA_REP' OR job_id = 'AD_PRES' )‏ AND salary > 15000; 1 2
  • 45.
  • 46.
  • 47.
  • 48. Displaying Data from Multiple Tables
  • 49.
  • 50. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … …
  • 51.
  • 52.
  • 53.
  • 54. Retrieving Records with Natural Joins SELECT department_id, department_name, location_id, city FROM departments NATURAL JOIN locations ;
  • 55.
  • 56. Joining Column Names EMPLOYEES DEPARTMENTS Foreign key Primary key … …
  • 57. Retrieving Records with the USING Clause SELECT employees.employee_id, employees.last_name, departments.location_id, department_id FROM employees JOIN departments USING (department_id) ; …
  • 58.
  • 59.
  • 60.
  • 61. Retrieving Records with the ON Clause SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id); …
  • 62. Self-Joins Using the ON Clause MANAGER_ID in the WORKER table is equal to EMPLOYEE_ID in the MANAGER table. EMPLOYEES (WORKER) EMPLOYEES (MANAGER) … …
  • 63. Self-Joins Using the ON Clause SELECT e.last_name emp, m.last_name mgr FROM employees e JOIN employees m ON (e.manager_id = m.employee_id); …
  • 64. Applying Additional Conditions to a Join SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id) AND e.manager_id = 149 ;
  • 65. Creating Three-Way Joins with the ON Clause SELECT employee_id, city, department_name FROM employees e JOIN departments d ON d.department_id = e.department_id JOIN locations l ON d.location_id = l.location_id; …
  • 66. Nonequijoins EMPLOYEES JOB_GRADES Salary in the EMPLOYEES table must be between lowest salary and highest salary in the JOB_GRADES table. …
  • 67. Retrieving Records with Nonequijoins SELECT e.last_name, e.salary, j.grade_level FROM employees e JOIN job_grades j ON e.salary BETWEEN j.lowest_sal AND j.highest_sal; …
  • 68. Outer Joins EMPLOYEES DEPARTMENTS There are no employees in department 190. …
  • 69.
  • 70. LEFT OUTER JOIN SELECT e.last_name, e.department_id, d.department_name FROM employees e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id) ; …
  • 71. RIGHT OUTER JOIN SELECT e.last_name, e.department_id, d.department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id) ; …
  • 72. FULL OUTER JOIN SELECT e.last_name, d.department_id, d.department_name FROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id) ; …
  • 73.
  • 74. Generating a Cartesian Product Cartesian product: 20 x 8 = 160 rows EMPLOYEES (20 rows) DEPARTMENTS (8 rows) … …
  • 75.
  • 76.
  • 78.
  • 79.
  • 80. Adding a New Row to a Table DEPARTMENTS New row Insert new row into the DEPARTMENTS table
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87. Changing Data in a Table EMPLOYEES Update rows in the EMPLOYEES table:
  • 88.
  • 89.
  • 90. Removing a Row from a Table Delete a row from the DEPARTMENTS table: DEPARTMENTS
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96. Controlling Transactions SAVEPOINT B SAVEPOINT A DELETE INSERT UPDATE INSERT COMMIT Time Transaction ROLLBACK to SAVEPOINT B ROLLBACK to SAVEPOINT A ROLLBACK
  • 97.
  • 98.
  • 99.  
  • 100.
  • 101.
  • 102.
  • 103.
  • 104. State of the Data After ROLLBACK DELETE FROM test; 25,000 rows deleted. ROLLBACK; Rollback complete. DELETE FROM test WHERE id = 100; 1 row deleted. SELECT * FROM test WHERE id = 100; No rows selected. COMMIT; Commit complete.
  • 105.
  • 106.
  • 107. Using DDL Statements to Create and Manage Tables
  • 108.
  • 109. Database Objects Logically represents subsets of data from one or more tables View Generates numeric values Sequence Basic unit of storage; composed of rows Table Gives alternative names to objects Synonym Improves the performance of some queries Index Description Object
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115. Data Types Raw binary data RAW and LONG RAW Binary data (up to 4 GB) BLOB Binary data stored in an external file (up to 4 GB) BFILE Date and time values DATE Variable-length character data (up to 2 GB) LONG Character data (up to 4 GB) CLOB A base-64 number system representing the unique address of a row in its table ROWID Fixed-length character data CHAR( size ) Variable-length numeric data NUMBER( p , s) Variable-length character data VARCHAR2( size ) Description Data Type
  • 116.  
  • 117.
  • 118.
  • 119.  
  • 120.
  • 121.  
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128. UNIQUE Constraint EMPLOYEES UNIQUE constraint INSERT INTO Not allowed: already exists Allowed …
  • 129.
  • 130. PRIMARY KEY Constraint DEPARTMENTS PRIMARY KEY INSERT INTO Not allowed (null value) Not allowed (50 already exists) …
  • 131. FOREIGN KEY Constraint DEPARTMENTS EMPLOYEES FOREIGN KEY INSERT INTO Not allowed (9 does not exist) Allowed PRIMARY KEY … …
  • 132.
  • 133.
  • 134.
  • 135. CREATE TABLE : Example CREATE TABLE employees ( employee_id NUMBER(6) CONSTRAINT emp_employee_id PRIMARY KEY , first_name VARCHAR2(20) , last_name VARCHAR2(25) CONSTRAINT emp_last_name_nn NOT NULL , email VARCHAR2(25) CONSTRAINT emp_email_nn NOT NULL CONSTRAINT emp_email_uk UNIQUE , phone_number VARCHAR2(20) , hire_date DATE CONSTRAINT emp_hire_date_nn NOT NULL , job_id VARCHAR2(10) CONSTRAINT emp_job_nn NOT NULL , salary NUMBER(8,2) CONSTRAINT emp_salary_ck CHECK (salary>0) , commission_pct NUMBER(2,2) , manager_id NUMBER(6) , department_id NUMBER(4) CONSTRAINT emp_dept_fk REFERENCES departments (department_id));
  • 136.
  • 137.
  • 138.
  • 139. Creating a Table by Using a Subquery CREATE TABLE dept80 AS SELECT employee_id, last_name, salary*12 ANNSAL, hire_date FROM employees WHERE department_id = 80; Table created. DESCRIBE dept80
  • 140.
  • 141.
  • 142.
  • 144.
  • 145.
  • 146.
  • 147. PL/SQL Environment PL/SQL Engine Oracle Database Server SQL Statement Executor Procedural Statement Executor procedural SQL PL/SQL Block
  • 148.
  • 149.
  • 151.
  • 153.
  • 155. Program Constructs Application triggers Application packages Application procedures or functions Anonymous blocks Tools Constructs Object types Database triggers Stored packages Stored procedures or functions Anonymous blocks Database Server Constructs Object types
  • 157.
  • 158.
  • 159.
  • 160.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166. Declaring and Initializing PL/SQL Variables Syntax: Examples: identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr ]; DECLARE emp_hiredate DATE; emp_deptno NUMBER(2) NOT NULL := 10; location VARCHAR2(13) := 'Atlanta'; c_comm CONSTANT NUMBER := 1400;
  • 167. Declaring and Initializing PL/SQL Variables SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20); BEGIN DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); Myname := 'John'; DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); END; / SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20):= 'John'; BEGIN Myname := 'Steven'; DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); END; / 1 2
  • 168. Delimiters in String Literals SET SERVEROUTPUT ON DECLARE event VARCHAR2(15); BEGIN event := q'!Father's day!'; DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is : '||event); event := q'[Mother's day]'; DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is : '||event); END; /
  • 169.
  • 170. Types of Variables TRUE 25-JAN-01 Atlanta 256120.08 The soul of the lazy man desires, and has nothing; but the soul of the diligent shall be made rich.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.  
  • 176.
  • 177.  
  • 178.
  • 179. BINARY_FLOAT and BINARY_DOUBLE
  • 180.
  • 181.
  • 182. The %TYPE Attribute
  • 183.
  • 184.
  • 185.
  • 186.  
  • 187.
  • 188.
  • 189.
  • 191. Prompt for Substitution Variables SET VERIFY OFF VARIABLE emp_salary NUMBER ACCEPT empno PROMPT 'Please enter a valid employee number: ' SET AUTOPRINT ON DECLARE empno NUMBER(6):= &empno; BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = empno; END; /
  • 192.
  • 193. Composite Data Types TRUE 23-DEC-98 ATLANTA 1 5000 2 2345 3 12 4 3456 1 SMITH 2 JONES 3 NANCY 4 TIM PL/SQL table structure PL/SQL table structure PLS_INTEGER VARCHAR2 PLS_INTEGER NUMBER
  • 194. LOB Data Type Variables Book ( CLOB ) Photo ( BLOB ) Movie ( BFILE ) NCLOB
  • 195.
  • 196. Interacting with the Oracle Server
  • 197.
  • 198.
  • 199. SQL Statements in PL/SQL
  • 200.
  • 201.  
  • 202.
  • 203. SELECT Statements in PL/SQL
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.  
  • 214.
  • 215.  
  • 216.
  • 217.
  • 218.
  • 220.
  • 221. Controlling Flow of Execution for loop while
  • 222.
  • 224. Simple IF Statement DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); END IF; END; /
  • 225. IF THEN ELSE Statement SET SERVEROUTPUT ON DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; /
  • 226. IF ELSIF ELSE Clause DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSIF myage < 20 THEN DBMS_OUTPUT.PUT_LINE(' I am young '); ELSIF myage < 30 THEN DBMS_OUTPUT.PUT_LINE(' I am in my twenties'); ELSIF myage < 40 THEN DBMS_OUTPUT.PUT_LINE(' I am in my thirties'); ELSE DBMS_OUTPUT.PUT_LINE(' I am always young '); END IF; END; /
  • 227. NULL Values in IF Statements DECLARE myage number; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; /
  • 228.
  • 229. CASE Expressions: Example SET SERVEROUTPUT ON SET VERIFY OFF DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal := CASE grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| grade || ' Appraisal ' || appraisal); END; /
  • 230. Searched CASE Expressions DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal := CASE WHEN grade = 'A' THEN 'Excellent' WHEN grade IN ('B','C') THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| grade || ' Appraisal ' || appraisal); END; /
  • 231. CASE Statement DECLARE deptid NUMBER; deptname VARCHAR2(20); emps NUMBER; mngid NUMBER:= 108; BEGIN CASE mngid WHEN 108 THEN SELECT department_id, department_name INTO deptid, deptname FROM departments WHERE manager_id=108; SELECT count(*) INTO emps FROM employees WHERE department_id=deptid; WHEN 200 THEN ... END CASE; DBMS_OUTPUT.PUT_LINE ('You are working in the '|| deptname|| ' department. There are '||emps ||' employees in this department'); END; /
  • 232.
  • 233.
  • 234.
  • 235.
  • 236.
  • 237.
  • 238.
  • 239.
  • 240.
  • 242.
  • 243.
  • 244.
  • 245.
  • 246. Nested Loops and Labels ... BEGIN <<Outer_loop>> LOOP counter := counter+1; EXIT WHEN counter>10; <<Inner_loop>> LOOP ... EXIT Outer_loop WHEN total_done = 'YES'; -- Leave both loops EXIT WHEN inner_ done = 'YES'; -- Leave inner loop only ... END LOOP Inner_loop ; ... END LOOP Outer_loop ; END; /
  • 247.
  • 248. Working with Composite Data Types
  • 249.
  • 250.
  • 251.
  • 252.
  • 253.
  • 254.
  • 255. PL/SQL Record Structure Example: 100 King AD_PRES employee_id number(6) last_name varchar2(25) job_id varchar2(10) Field2 (data type) Field3 (data type) Field1 (data type) Field2 (data type) Field3 (data type) Field1 (data type)
  • 256.
  • 257.
  • 258.
  • 259. The %ROWTYPE Attribute ... DEFINE employee_number = 124 DECLARE emp_rec employees%ROWTYPE; BEGIN SELECT * INTO emp_rec FROM employees WHERE employee_id = &employee_number; INSERT INTO retired_emps(empno, ename, job, mgr, hiredate, leavedate, sal, comm, deptno) VALUES (emp_rec.employee_id, emp_rec.last_name, emp_rec.job_id,emp_rec.manager_id, emp_rec.hire_date, SYSDATE, emp_rec.salary, emp_rec.commission_pct, emp_rec.department_id); END; /
  • 260. Inserting a Record Using %ROWTYPE ... DEFINE employee_number = 124 DECLARE emp_rec retired_emps%ROWTYPE; BEGIN SELECT employee_id, last_name, job_id, manager_id, hire_date, hire_date, salary, commission_pct, department_id INTO emp_rec FROM employees WHERE employee_id = &employee_number; INSERT INTO retired_emps VALUES emp_rec; END; / SELECT * FROM retired_emps;
  • 261. Updating a Row in a Table Using a Record SET SERVEROUTPUT ON SET VERIFY OFF DEFINE employee_number = 124 DECLARE emp_rec retired_emps%ROWTYPE; BEGIN SELECT * INTO emp_rec FROM retired_emps; emp_rec.leavedate:=SYSDATE; UPDATE retired_emps SET ROW = emp_rec WHERE empno=&employee_number; END; / SELECT * FROM retired_emps;
  • 262.
  • 263.
  • 264. Creating an INDEX BY Table
  • 265. INDEX BY Table Structure Unique Key Value ... ... 1 Jones 5 Smith 3 Maduro ... ... PLS_INTEGER Scalar
  • 266.
  • 267.
  • 268.
  • 269. INDEX BY Table of Records
  • 270. Example of INDEX BY Table of Records SET SERVEROUTPUT ON DECLARE TYPE emp_table_type IS TABLE OF employees%ROWTYPE INDEX BY PLS_INTEGER; my_emp_table emp_table_type; max_count NUMBER(3):= 104; BEGIN FOR i IN 100..max_count LOOP SELECT * INTO my_emp_table(i) FROM employees WHERE employee_id = i; END LOOP; FOR i IN my_emp_table.FIRST..my_emp_table.LAST LOOP DBMS_OUTPUT.PUT_LINE(my_emp_table(i).last_name); END LOOP; END; /
  • 271.
  • 273.
  • 274.
  • 275. Explicit Cursor Operations Active set Table 100 King AD_PRES 101 Kochhar AD_VP 102 De Haan AD_VP . . . . . . . . . 139 Seo ST_CLERK 140 Patel ST_CLERK . . .
  • 276.
  • 277. Controlling Explicit Cursors Fetch a row. Close the cursor. Cursor pointer Open the cursor. 1 2 3 Cursor pointer Cursor pointer
  • 278.
  • 280. Opening the Cursor DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; ... BEGIN OPEN emp_cursor;
  • 281. Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; empno employees.employee_id%TYPE; lname employees.last_name%TYPE; BEGIN OPEN emp_cursor; FETCH emp_cursor INTO empno, lname; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname); ... END; /
  • 282. Fetching Data from the Cursor
  • 283. Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; empno employees.employee_id%TYPE; lname employees.last_name%TYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO empno, lname; EXIT WHEN emp_cursor%NOTFOUND ; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname); END LOOP; ... END; /
  • 284. Closing the Cursor ... LOOP FETCH emp_cursor INTO empno, lname; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname); END LOOP; CLOSE emp_cursor; END; /
  • 285.
  • 286.
  • 287. Cursor FOR Loops SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; BEGIN FOR emp_record IN emp_cursor LOOP DBMS_OUTPUT.PUT_LINE( emp_record.employee_id ||' ' || emp_record.last_name ); END LOOP; END; /
  • 288.
  • 289.
  • 290. Example of %ROWCOUNT and %NOTFOUND SET SERVEROUTPUT ON DECLARE empno employees.employee_id%TYPE; ename employees.last_name%TYPE; CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO empno, ename; EXIT WHEN emp_cursor%ROWCOUNT > 10 OR emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE(TO_CHAR(empno) ||' '|| ename); END LOOP; CLOSE emp_cursor; END ; /
  • 291.
  • 292.
  • 293. Cursors with Parameters SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor (deptno NUMBER) IS SELECT employee_id, last_name FROM employees WHERE department_id = deptno; dept_id NUMBER; lname VARCHAR2(15); BEGIN OPEN emp_cursor (10); ... CLOSE emp_cursor; OPEN emp_cursor (20); ...
  • 294.
  • 295. The FOR UPDATE Clause
  • 296.
  • 297. Cursors with Subqueries DECLARE CURSOR my_cursor IS SELECT t1.department_id, t1.department_name, t2.staff FROM departments t1, (SELECT department_id, COUNT(*) AS STAFF FROM employees GROUP BY department_id) t2 WHERE t1.department_id = t2.department_id AND t2.staff >= 3; ... Example:
  • 298.
  • 300.
  • 301. Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE first_name='John'; DBMS_OUTPUT.PUT_LINE ('John''s last name is : ' ||lname); END; /
  • 302. Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE first_name='John'; DBMS_OUTPUT.PUT_LINE ('John''s last name is : ' ||lname); EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE (' Your select statement retrieved multiple rows. Consider using a cursor.'); END; /
  • 303.
  • 304. Handling Exceptions Exception raised Is the exception trapped? yes Execute statements in the EXCEPTION section Terminate gracefully no Terminate abruptly Propagate the exception
  • 305.
  • 306.
  • 308.
  • 309.
  • 310.  
  • 311.  
  • 312. Trapping Non-Predefined Oracle Server Errors Declarative section Name the exception Code PRAGMA EXCEPTION_INIT EXCEPTION section Handle the raised exception Associate Reference Declare
  • 313.
  • 314.
  • 315.
  • 316. Trapping User-Defined Exceptions Declarative section Name the exception. Executable section Explicitly raise the exception by using the RAISE statement. Exception -handling section Handle the raised exception. Raise Reference Declare
  • 317. Trapping User-Defined Exceptions ... ACCEPT deptno PROMPT 'Please enter the department number:' ACCEPT name PROMPT 'Please enter the department name:' DECLARE invalid_department EXCEPTION; name VARCHAR2(20):='&name'; deptno NUMBER :=&deptno; BEGIN UPDATE departments SET department_name = name WHERE department_id = deptno; IF SQL%NOTFOUND THEN RAISE invalid_department; END IF; COMMIT; EXCEPTION WHEN invalid_department THEN DBMS_OUTPUT.PUT_LINE('No such department id.'); END; / 1 2 3
  • 318. Calling Environments Traps exception in exception-handling routine of enclosing block An enclosing PL/SQL block Accesses exception number through the SQLCA data structure Precompiler application Accesses error number and message in an ON-ERROR trigger by means of the ERROR_CODE and ERROR_TEXT packaged functions Oracle Developer Forms Displays error number and message to screen Procedure Builder Displays error number and message to screen i SQL*Plus
  • 319. Propagating Exceptions in a Subblock DECLARE . . . no_rows exception; integrity exception; PRAGMA EXCEPTION_INIT (integrity, -2292); BEGIN FOR c_record IN emp_cursor LOOP BEGIN SELECT ... UPDATE ... IF SQL%NOTFOUND THEN RAISE no_rows; END IF; END; END LOOP; EXCEPTION WHEN integrity THEN ... WHEN no_rows THEN ... END; / Subblocks can handle an exception or pass the exception to the enclosing block.
  • 320.
  • 321.
  • 322.
  • 323.
  • 324. Creating Stored Procedures and Functions
  • 325.
  • 326.
  • 327. Differences Between Anonymous Blocks and Subprograms Can take parameters Cannot take parameters Subprograms called functions must return values Do not return values They are named and therefore can be invoked by other applications Cannot be invoked by other applications Stored in the database Not stored in the database Compiled only once Compiled every time Named PL/SQL blocks Unnamed PL/SQL blocks Subprograms Anonymous Blocks
  • 328. Procedure: Syntax CREATE [OR REPLACE] PROCEDURE procedure_name [( argument1 [ mode1 ] datatype1, argument2 [ mode2 ] datatype2, . . . )] IS|AS procedure_body;
  • 329. Procedure: Example ... CREATE TABLE dept AS SELECT * FROM departments; CREATE PROCEDURE add_dept IS dept_id dept.department_id%TYPE; dept_name dept.department_name%TYPE; BEGIN dept_id:=280; dept_name:= ' ST-Curriculum ' ; INSERT INTO dept(department_id,department_name) VALUES(dept_id,dept_name); DBMS_OUTPUT.PUT_LINE( ' Inserted ' || SQL%ROWCOUNT || ' row ' ); END; /
  • 331. Invoking the Procedure BEGIN add_dept; END; / SELECT department_id, department_name FROM dept WHERE department_id=280;
  • 332. Function: Syntax C REATE [OR REPLACE] FUNCTION function_name [( argument1 [ mode1 ] datatype1, argument2 [ mode2 ] datatype2, . . . )] RETURN datatype IS|AS function_body;
  • 333. Function: Example CREATE FUNCTION check_sal RETURN Boolean IS dept_id employees.department_id%TYPE; empno employees.employee_id%TYPE; sal employees.salary%TYPE; avg_sal employees.salary%TYPE; BEGIN empno:=205; SELECT salary,department_id INTO sal,dept_id FROM employees WHERE employee_id= empno; SELECT avg(salary) INTO avg_sal FROM employees WHERE department_id=dept_id; IF sal > avg_sal THEN RETURN TRUE; ELSE RETURN FALSE; END IF; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL; END; /
  • 334. Invoking the Function SET SERVEROUTPUT ON BEGIN IF (check_sal IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal) THEN DBMS_OUTPUT.PUT_LINE('Salary > average'); ELSE DBMS_OUTPUT.PUT_LINE('Salary < average'); END IF; END; /
  • 335. Passing Parameter to the Function DROP FUNCTION check_sal; / CREATE FUNCTION check_sal (empno employees.employee_id%TYPE) RETURN Boolean IS dept_id employees.department_id%TYPE; sal employees.salary%TYPE; avg_sal employees.salary%TYPE; BEGIN SELECT salary,department_id INTO sal,dept_id FROM employees WHERE employee_id=empno; SELECT avg(salary) INTO avg_sal FROM employees WHERE department_id=dept_id; IF sal > avg_sal THEN RETURN TRUE; ELSE RETURN FALSE; END IF; EXCEPTION ... ...
  • 336. Invoking the Function with a Parameter BEGIN DBMS_OUTPUT.PUT_LINE('Checking for employee with id 205'); IF (check_sal(205) IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal(205)) THEN DBMS_OUTPUT.PUT_LINE('Salary > average'); ELSE DBMS_OUTPUT.PUT_LINE('Salary < average'); END IF; DBMS_OUTPUT.PUT_LINE('Checking for employee with id 70'); IF (check_sal(70) IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal(70)) THEN ... END IF; END; /
  • 337.
  • 338.