Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to PL-SQL Introduction to PL-SQL Aj. ประวัฒน์ เปรมธีรสมบูรณ์ Lecture by.

Similar presentations


Presentation on theme: "Introduction to PL-SQL Introduction to PL-SQL Aj. ประวัฒน์ เปรมธีรสมบูรณ์ Lecture by."— Presentation transcript:

1 Introduction to PL-SQL Introduction to PL-SQL Aj. ประวัฒน์ เปรมธีรสมบูรณ์ prawat237@yahoo.com Lecture by

2 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 2 Objectives After completing this lesson, you should be able to do the following: –List the benefits of PL/SQL –Recognize the basic PL/SQL block and its sections –Describe the significance of variables in PL/SQL –Declare PL/SQL variables –Execute a PL/SQL block

3 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 3 Objectives (Con ’ t) After completing this lesson, you should be able to do the following: –Recognize the significance of the executable section –Write statements in the executable section –Describe the rules of nested blocks –Execute and test a PL/SQL block –Use coding conventions

4 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 4 What is PL/SQL? PL/SQL is an extension to SQL with design features of programming languages. Data manipulation and query statements of SQL are included within procedural units of code. ProceduralLanguageExtension toSQLPL/SQL

5 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 5 Benefits of PL/SQL Integration Application Oracle Server Sharedlibrary

6 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 6 Benefits of PL/SQL Improved Performance Application Other DBMSs Application Oracle with PL/SQL SQL SQL SQLSQLSQL IF...THEN SQLELSESQL END IF; SQL

7 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 7 Benefits of PL/SQL Modularize program development DECLARE BEGIN EXCEPTION END;

8 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 8 Benefits of PL/SQL It is portable. You can declare identifiers. You can program with procedural language control structures. It can handle errors.

9 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 9 PL/SQL Block Structure DECLARE – Optional – Variables, cursors, user-defined exceptions BEGIN – Mandatory – SQL statements – PL/SQL statements EXCEPTION – Optional – Actions to perform when errors occur END; – Mandatory DECLARE – Optional – Variables, cursors, user-defined exceptions BEGIN – Mandatory – SQL statements – PL/SQL statements EXCEPTION – Optional – Actions to perform when errors occur END; – Mandatory DECLARE BEGIN EXCEPTION END;

10 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 10 PL/SQL Block Structure DECLARE v_variable VARCHAR2(5); BEGIN SELECTcolumn_name INTOv_variable FROMtable_name; EXCEPTION WHEN exception_name THEN... END; DECLARE v_variable VARCHAR2(5); BEGIN SELECTcolumn_name INTOv_variable FROMtable_name; EXCEPTION WHEN exception_name THEN... END; DECLARE BEGIN EXCEPTION END;

11 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 11 Block Types PL/SQL code is built of Blocks, with a unique structure There are two types of blocks in PL/SQL -: 1.Anonymous Blocks : have no name (like scripts) –Can be written and executed immediately in SQLPLUS –Can be used in a trigger 2.Named Blocks : –Procedures –Functions

12 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 12 Block Types AnonymousProcedureFunction [DECLARE] BEGIN --statements --statements [EXCEPTION] END; [DECLARE] BEGIN --statements --statements [EXCEPTION] END; PROCEDURE name ISBEGIN --statements --statements [EXCEPTION] END; PROCEDURE name ISBEGIN --statements --statements [EXCEPTION] END; FUNCTION name RETURN datatype ISBEGIN --statements --statements RETURN value; RETURN value; [EXCEPTION] END; FUNCTION name RETURN datatype ISBEGIN --statements --statements RETURN value; RETURN value; [EXCEPTION] END;

13 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 13 Program Constructs Anonymous block Application trigger Stored procedure/ function Database trigger Application procedure/ function Packaged procedure/ function function DECLARE BEGIN EXCEPTION END;

14 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 14 Use of Variables Use variables for: Temporary storage of data Manipulation of stored values Reusability Ease of maintenance

15 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 15 Handling Variables in PL/SQL Declare and initialize variables in the declaration section. Assign new values to variables in the executable section. Pass values into PL/SQL blocks through parameters. View results through output variables.

16 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 16 Types of Variables PL/SQL variables: –Scalar –Composite –Reference –LOB (large objects) Non-PL/SQL variables: Bind and host variables

17 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 17 Types of Variables PL/SQL variables: –Scalar –Composite –Reference –LOB (large objects) Non-PL/SQL variables: Bind and host variables

18 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 18 Types of Variables TRUE 25-OCT-99 “Four score and seven years ago our fathers brought forth upon this continent, a new nation, conceived in LIBERTY, and dedicated to the proposition that all men are created equal.” 256120.08 Atlanta

19 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 19 Declaring PL/SQL Variables SyntaxSyntax ExamplesExamples identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; Declare v_hiredateDATE; v_deptnoNUMBER(2) NOT NULL := 10; v_locationVARCHAR2(13) := 'Atlanta'; c_commCONSTANT NUMBER := 1400; Declare v_hiredateDATE; v_deptnoNUMBER(2) NOT NULL := 10; v_locationVARCHAR2(13) := 'Atlanta'; c_commCONSTANT NUMBER := 1400;

20 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 20 Declaring PL/SQL Variables Guidelines –Follow naming conventions. –Initialize variables designated as NOT NULL. –Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word. –Declare at most one identifier per line.

21 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 21 Naming Rules Two variables can have the same name, provided they are in different blocks. The variable name (identifier) should not be the same as the name of table columns used in the block. DECLARE empnoNUMBER(4); BEGIN SELECTempno INTOempno FROMemp WHERE ename = 'SMITH'; END; DECLARE empnoNUMBER(4); BEGIN SELECTempno INTOempno FROMemp WHERE ename = 'SMITH'; END; Adopt a naming convention for PL/SQL identifiers: for example, v_empno

22 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 22 Assigning Values to Variables SyntaxSyntax ExamplesExamples –Set a predefined hiredate for new employees. –Set the employee name to “Maduro.” v_ename := 'Maduro'; v_hiredate := '31-DEC-98'; identifier := expr;

23 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 23 Scalar Datatypes Hold a single value Have no internal components Atlanta “Four score and seven years ago our fathers brought forth upon this continent, a new nation, conceived in LIBERTY, and dedicated to the proposition that all men are created equal.” TRUE 256120.08 25-OCT-99

24 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 24 Base Scalar Datatypes VARCHAR2 (maximum_length) NUMBER [(precision, scale)] DATE CHAR [(maximum_length)] LONG LONG RAW BOOLEAN BINARY_INTEGER PLS_INTEGER

25 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 25 Scalar Variable Declarations Examples v_jobVARCHAR2(9); v_countBINARY_INTEGER := 0; v_total_salNUMBER(9,2) := 0; v_orderdateDATE := SYSDATE + 7; c_tax_rateCONSTANT NUMBER(3,2) := 8.25; v_validBOOLEAN NOT NULL := TRUE; v_jobVARCHAR2(9); v_countBINARY_INTEGER := 0; v_total_salNUMBER(9,2) := 0; v_orderdateDATE := SYSDATE + 7; c_tax_rateCONSTANT NUMBER(3,2) := 8.25; v_validBOOLEAN NOT NULL := TRUE;

26 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 26 Controlling PL/SQL Flow of Execution You can change the logical flow of statements using conditional IF statements and loop control structures. Conditional IF statements: –IF-THEN-END IF –IF-THEN-ELSE-END IF –IF-THEN-ELSIF-END IF

27 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 27 IF Statements Syntax Simple IF statement: Set the manager ID to 22 if the employee name is Osborne. IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF; IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF; IF v_ename = 'OSBORNE' THEN v_mgr := 22; END IF; IF v_ename = 'OSBORNE' THEN v_mgr := 22; END IF;

28 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 28 Simple IF Statements Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller. Example... IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;... IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;...

29 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 29 IF-THEN-ELSE Statement Execution Flow IF condition TRUE THEN actions (including further IFs) THEN actions (including further IFs) FALSE ELSE actions (including further IFs) ELSE actions (including further IFs)

30 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 30 IF-THEN-ELSE Statements Set a flag for orders where there are fewer than five days between order date and ship date. Example... IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable'; ELSE v_ship_flag := 'Unacceptable'; END IF;... IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable'; ELSE v_ship_flag := 'Unacceptable'; END IF;...

31 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 31 IF-THEN-ELSIF Statement Execution Flow IF condition TRUE THEN actions FALSE ELSIFconditionELSIFcondition TRUE FALSE ELSEactionsELSEactions

32 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 32 IF-THEN-ELSIF Statements For a given value, calculate a percentage of that value based on a condition. Example... IF v_start > 100 THEN v_start := 2 * v_start; ELSIF v_start >= 50 THEN v_start :=.5 * v_start; ELSE v_start :=.1 * v_start; END IF;... IF v_start > 100 THEN v_start := 2 * v_start; ELSIF v_start >= 50 THEN v_start :=.5 * v_start; ELSE v_start :=.1 * v_start; END IF;...

33 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 33 Building Logical Conditions You can handle null values with the IS NULL operator. Any arithmetic expression containing a null value evaluates to NULL. Concatenated expressions with null values treat null values as an empty string.

34 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 34 Logic Tables Build a simple Boolean condition with a comparison operator. NOT TRUE FALSE NULL OR TRUE FALSE NULL TRUEFALSENULL FALSE TRUE NULL AND TRUE FALSE NULL TRUEFALSENULL TRUE NULL FALSE TRUE FALSE NULL

35 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 35 Boolean Conditions What is the value of V_FLAG in each case? v_flag := v_reorder_flag AND v_available_flag; V_REORDER_FLAGV_AVAILABLE_FLAGV_FLAG TRUE TRUEFALSE NULLTRUE NULLFALSE TRUEFALSENULLFALSE

36 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 36 Iterative Control: LOOP Statements Loops repeat a statement or sequence of statements multiple times. There are three loop types: –Basic loop –FOR loop –WHILE loop

37 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 37 Basic Loop Syntax LOOP statement1;... EXIT [WHEN condition]; END LOOP; LOOP statement1;... EXIT [WHEN condition]; END LOOP; where:conditionis a Boolean variable or expression (TRUE, FALSE, or NULL); where:conditionis a Boolean variable or expression (TRUE, FALSE, or NULL);

38 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 38 Basic Loop Example DECLARE v_ordiditem.ordid%TYPE := 601; v_counterNUMBER(2) := 1; BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP; END; DECLARE v_ordiditem.ordid%TYPE := 601; v_counterNUMBER(2) := 1; BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP; END;

39 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 39 FOR Loop Syntax Use a FOR loop to shortcut the test for the number of iterations. Do not declare the index; it is declared implicitly. FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; statement2;... END LOOP; FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; statement2;... END LOOP;

40 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 40 FOR Loop Guidelines Reference the counter within the loop only; it is undefined outside the loop. Use an expression to reference the existing value of a counter. Do not reference the counter as the target of an assignment.

41 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 41 FOR Loop Insert the first 10 new line items for order number 601. Example DECLARE v_ordiditem.ordid%TYPE := 601; BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP; END; DECLARE v_ordiditem.ordid%TYPE := 601; BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP; END;

42 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 42 WHILE Loop Syntax Use the WHILE loop to repeat statements while a condition is TRUE. WHILE condition LOOP statement1; statement2;... END LOOP; WHILE condition LOOP statement1; statement2;... END LOOP; Condition is evaluated at the beginning of each iteration.

43 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 43 WHILE Loop Example ACCEPT p_new_order PROMPT 'Enter the order number: ' ACCEPT p_items - PROMPT 'Enter the number of items in this order: ' DECLARE v_countNUMBER(2) := 1; BEGIN WHILE v_count <= &p_items LOOP INSERT INTO item (ordid, itemid) VALUES (&p_new_order, v_count); v_count := v_count + 1; END LOOP; COMMIT; END; / ACCEPT p_new_order PROMPT 'Enter the order number: ' ACCEPT p_items - PROMPT 'Enter the number of items in this order: ' DECLARE v_countNUMBER(2) := 1; BEGIN WHILE v_count <= &p_items LOOP INSERT INTO item (ordid, itemid) VALUES (&p_new_order, v_count); v_count := v_count + 1; END LOOP; COMMIT; END; /

44 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 44 The %TYPE Attribute Declare a variable according to: –A database column definition –Another previously declared variable Prefix %TYPE with: –The database table and column –The previously declared variable name

45 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 45 Declaring Variables with the %TYPE Attribute Examples... v_enameemp.ename%TYPE; v_balance NUMBER(7,2); v_min_balancev_balance%TYPE := 10;... v_enameemp.ename%TYPE; v_balance NUMBER(7,2); v_min_balancev_balance%TYPE := 10;...

46 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 46 SELECT Statements in PL/SQL Retrieve data from the database with SELECT. Syntax SELECT select_list INTO {variable_name[, variable_name]... | record_name} FROM table WHERE condition; SELECT select_list INTO {variable_name[, variable_name]... | record_name} FROM table WHERE condition;

47 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 47 DECLARE v_employee tbl_m_employee%ROWTYPE; BEGIN SELECT * INTO v_employee FROM tbl_m_employee WHERE emp_code=10001; EXCEPTION WHEN no_data_found THEN DBMS_OUTPUT.PUT_LINE('No Data Found'); END;

48 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 48 SELECT Statements in PL/SQL The INTO clause is required. Example DECLARE v_deptnoNUMBER(2); v_locVARCHAR2(15); BEGIN SELECTdeptno, loc INTOv_deptno, v_loc FROMdept WHEREdname = 'SALES';... END; DECLARE v_deptnoNUMBER(2); v_locVARCHAR2(15); BEGIN SELECTdeptno, loc INTOv_deptno, v_loc FROMdept WHEREdname = 'SALES';... END;

49 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 49 Retrieving Data in PL/SQL Retrieve the order date and the ship date for the specified order. Example DECLARE v_orderdate ord.orderdate%TYPE; v_shipdate ord.shipdate%TYPE; BEGIN SELECT orderdate, shipdate INTO v_orderdate, v_shipdate FROM ord WHERE id = 620;... END; DECLARE v_orderdate ord.orderdate%TYPE; v_shipdate ord.shipdate%TYPE; BEGIN SELECT orderdate, shipdate INTO v_orderdate, v_shipdate FROM ord WHERE id = 620;... END;

50 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 50 Retrieving Data in PL/SQL Return the sum of the salaries for all employees in the specified department. Example DECLARE v_sum_sal emp.sal%TYPE; v_deptno NUMBER NOT NULL := 10; BEGIN SELECTSUM(sal) -- group function INTOv_sum_sal FROMemp WHEREdeptno = v_deptno; END; DECLARE v_sum_sal emp.sal%TYPE; v_deptno NUMBER NOT NULL := 10; BEGIN SELECTSUM(sal) -- group function INTOv_sum_sal FROMemp WHEREdeptno = v_deptno; END;

51 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 51 Manipulating Data Using PL/SQL Make changes to database tables by using DML commands: –INSERT –UPDATE –DELETE INSERT UPDATE DELETE

52 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 52 Inserting Data Add new employee information to the emp table. Example BEGIN INSERT INTO emp(empno, ename, job, deptno) VALUES(empno_seq.NEXTVAL, 'HARDING', 'CLERK', 10); END; BEGIN INSERT INTO emp(empno, ename, job, deptno) VALUES(empno_seq.NEXTVAL, 'HARDING', 'CLERK', 10); END;

53 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 53 Inserting Data Same example using a procedure CREATE OR REPLACE PROCEDURE new_emp (en emp.ename%TYPE, jt emp.job%TYPE, sl emp.sal%TYPE, dn emp.deptno%TYPE) IS msg VARCHAR2(30); BEGIN INSERT INTO emp (empno, ename, job, sal, deptno) VALUES (empno_seq.NEXTVAL, en, jt, sl, dn); msg := (SQL%ROWCOUNT || ' row inserted '); DBMS_OUTPUT.PUT_LINE(msg); END; / CREATE OR REPLACE PROCEDURE new_emp (en emp.ename%TYPE, jt emp.job%TYPE, sl emp.sal%TYPE, dn emp.deptno%TYPE) IS msg VARCHAR2(30); BEGIN INSERT INTO emp (empno, ename, job, sal, deptno) VALUES (empno_seq.NEXTVAL, en, jt, sl, dn); msg := (SQL%ROWCOUNT || ' row inserted '); DBMS_OUTPUT.PUT_LINE(msg); END; /

54 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 54 Updating Data Increase the salary of all employees in the emp table who are Analysts. Example DECLARE v_sal_increase emp.sal%TYPE := 2000; BEGIN UPDATEemp SETsal = sal + v_sal_increase WHEREjob = 'ANALYST'; END;

55 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 55 Deleting Data Delete rows that belong to department 10 from the emp table. Example DECLARE v_deptno emp.deptno%TYPE := 10; BEGIN DELETE FROM emp WHERE deptno = v_deptno; END; DECLARE v_deptno emp.deptno%TYPE := 10; BEGIN DELETE FROM emp WHERE deptno = v_deptno; END;

56 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 56 SQL Cursor A cursor is a private SQL work area. There are two types of cursors: –Implicit cursors –Explicit cursors The Oracle Server uses implicit cursors to parse and execute your SQL statements. Explicit cursors are explicitly declared by the programmer.

57 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 57 SQL Cursor Attributes Using SQL cursor attributes, you can test the outcome of your SQL statements. SQL%ROWCOUNTNumber of rows affected by the most recent SQL statement (an integervalue) SQL%FOUNDBoolean attribute that evaluates to TRUE if the most recent SQL statement affects oneor more rows SQL%NOTFOUNDBoolean attribute that evaluates to TRUE if the most recent SQL statement does not affect any rows SQL%ISOPENAlways evaluates to FALSE because PL/SQL closes implicit cursors immediately after they are executed

58 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 58 วิธีใช้ Explicit Cursor การใช้ explicit cursor มี 4 ขั้นตอน 1) ประกาศ cursor (Declare cursor) 2) เปิด cursor (Open cursor) 3) ดึงข้อมูลจาก cursor ครั้งละ 1 row (Fetch data from cursor) 4) ปิด cursor (Close cursor)

59 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 59 DECLARE 1) CURSOR cs_emp IS SELECT emp_name, salary FROM tbl_m_employee; v_emp_name tbl_m_employee.emp_name%TYPE; v_salary tbl_m_employee.salary%TYPE; BEGIN 2) OPEN cs_emp; LOOP 3) FETCH cs_emp INTO v_emp_name, v_salary; EXIT WHEN cs_emp%NOTFOUND; DBMS_OUTPUT.PUT_LINE(v_emp_name||' : '||v_salary); END LOOP; 4) CLOSE cs_emp; END; ตัวอย่าง : แสดงเงินเดือนพนักงานทุกคนโดยใช้ Explicit cursor

60 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 60 ผลลัพธ์ EMP_01 : 25000 EMP_02 : 78000 EMP_03 : 11000 EMP_04 : 8000 EMP_05 : 43000

61 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 61 SQL Cursor Attributes Delete rows that have the specified order number from the ITEM table. Print the number of rows deleted. Example VARIABLE rows_deleted VARCHAR2(30) DECLARE v_ordid NUMBER := 605; BEGIN DELETE FROM item WHERE ordid = v_ordid; :rows_deleted := (SQL%ROWCOUNT || ' rows deleted.'); END; / PRINT rows_deleted

62 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 62 Handling Exceptions with PL/SQL What is an exception? –Identifier in PL/SQL that is raised during execution How is it raised? –An Oracle error occurs. –You raise it explicitly. How do you handle it? –Trap it with a handler. –Propagate it to the calling environment.

63 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 63 Handling Exceptions Trap the exception DECLARE BEGIN END; Exception is raised EXCEPTION Exception is trapped Propagate the exception DECLARE BEGIN END; Exception is raised EXCEPTION Exception is not trapped Exception propagates to calling environment

64 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 64 Trapping Exceptions Syntax EXCEPTION WHEN exception1 [OR exception2...] THEN statement1; statement2;... [WHEN exception3 [OR exception4...] THEN statement1; statement2;...] [WHEN OTHERS THEN statement1; statement2;...] EXCEPTION WHEN exception1 [OR exception2...] THEN statement1; statement2;... [WHEN exception3 [OR exception4...] THEN statement1; statement2;...] [WHEN OTHERS THEN statement1; statement2;...]

65 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 65 Trapping Predefined Oracle Server Errors Reference the standard name in the exception-handling routine. Sample predefined exceptions: –NO_DATA_FOUND –TOO_MANY_ROWS –INVALID_CURSOR –ZERO_DIVIDE –DUP_VAL_ON_INDEX

66 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 66 Predefined Exception BEGIN SELECT... COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN statement1; statement2; WHEN TOO_MANY_ROWS THEN statement1; WHEN OTHERS THEN statement1; statement2; statement3; END;

67 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 67 แบบฝึกหัด 1. สร้าง anonymous block เพื่อแสดง “My PL/SQL Block Works” บน screen. My PL/SQL Block Works 2. สร้าง anonymous block เพื่อคำนวณ x:=2; y:=4; z= x+y; แสดงผลลัพธ์ z 3. จากข้อ 3 ใช้ IF กำหนดเงื่อนไขถ้า z มากกว่า 3 ให้แสดงข้อความ z > 3 ถ้า ไม่ให้แสดง z <=3

68 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 68 4. จงสร้างโปรแกรม PL/SQL ที่ทำการพิมพ์ employee_id, first_name และ salary ของ พนักงานที่มีรหัสพนักงาน 100 จาก Table ชื่อ EMPLOYEES [ ดูตัวอย่างที่ 9] 5. จงสร้างโปรแกรม PL/SQL ที่ทำการพิมพ์ employee_id, first_name และ salary ของ พนักงานทุกคนจาก Table ชื่อ EMPLOYEES [ ใช้ cursor ดูตัวอย่างที่ 10] 6. จากข้อ 5 แสดงเฉพาะพนักงานที่มีเงินเดือน มากกว่า 8000 [ ใช้ if ] 7. จากข้อ 5. ทำการแก้ไขเงินเดือนของพนักงานที่ น้อยกว่า 10000 ปรับค่าให้เป็น 10000 และมากกว่า 15000 ปรับให้ เหลือ 15000 [ ดูตัวอย่างที่ 14]

69 June 25, 2006 Aj.Winyou Niranartlamphong Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., Week 9 Introduction to PL-SQL., page 69 แบบฝึกหัด 8. สร้างตารางชื่อ Emp (empid,fname,salary) นำข้อมูลจากตาราง Employees เฉพาะ พนักงานที่มีเงินเดือน มากกว่า 5000 โดย กำหนดให้ Empid= 1001 บวกเพิ่มทีละ 1 Fname = first__name+last_name Salay =salary +1000


Download ppt "Introduction to PL-SQL Introduction to PL-SQL Aj. ประวัฒน์ เปรมธีรสมบูรณ์ Lecture by."

Similar presentations


Ads by Google