L9 l10 server side programming

524 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
524
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
23
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • BEGIN NULL; END; This is a valid PL/SQL block that does nothing! Try without ‘NULL;’ statement, see what happens!
  • Not stored in Oracle Server, Not named Executed in the same session and can not be called from another session To execute again, re-type the code or save it to a OS file and run it
  • The output of the block shown in the slide is as follows: Father_name Patrick Date of Birth 12-Dec-2002 Childs Name Mike Date of birth 20 Apr 1972 Examine the date of birth that is printed for father and child. The scope of a variable is the portion of the program in which the variable is declared and is accessible. The visibility of a variable is the portion of the program where the variable can be accessed without using a qualifier. Scope • The variables father_name and date_of_birth are declared in the outer block. These variables will have the scope of the block in which they are declared and accessible. Therefore, the scope of these variables are limited to the outer block. Scope (continued) • The variables child_name and date_of_birth are declared in the inner block or the nested block. These variables are accessible only within the nested block and are not accessible in the outer block. When a variable is out of scope, PL/SQL frees the memory used to store the variable and therefore these variables cannot be referenced. Visibility • The date_of_birth variable declared in the outer block has the scope even in the inner block. However, this variable is not visible in the inner block because the inner block has a local variable with the same name. 1. Observe the code in the executable section of the PL/SQL block. You can print the father’s name, the child’s name, and the date of birth. Only the child’s date of birth can be printed here because the father’s date of birth is not visible here. 2. Father’s date of birth is visible here and therefore can be printed. You cannot have variables with same name in a block. However, you can declare variables with same name in two different blocks (nested blocks). The two items represented by the identifiers are distinct, and any change in one does not affect the other.
  • You can write INSERT, UPDATE, and DELETE statements directly in PL/SQL programs, without any special notation:
  • Control structures are the most important PL/SQL extension to SQL. Not only does PL/SQL let you manipulate Oracle data, it lets you process the data using conditional, iterative, and sequential flow-of-control statements such as IF-THEN-ELSE, CASE, FOR-LOOP, WHILE-LOOP, EXIT-WHEN, and GOTO.
  • The sequence of statements is executed only if the condition is true. If the condition is false or null, the IF statement does nothing. In either case, control passes to the next statement. An example follows:
  • Consider the program below, which processes a bank transaction. Before allowing you to withdraw $500 from account 3, it makes sure the account has sufficient funds to cover the withdrawal. If the funds are available, the program debits the account. Otherwise, the program inserts a record into an audit table.
  • Writing Reusable PL/SQL Code PL/SQL lets you break an application down into manageable, well-defined modules. PL/SQL meets this need with program units , which include blocks, subprograms, and packages. You can reuse program units by loading them into the database as triggers, stored procedures, and stored functions.
  • When called, this procedure accepts an employee number. It uses the number to select the employee's commission from a database table and, at the same time, compute a 15% bonus. Then, it checks the bonus amount. If the bonus is null, an exception is raised; otherwise, the employee's payroll record is updated.
  • Packages are database objects that are a step above regular stored procedures
  • The following example packages two employment procedures: Applications that call these procedures only need to know the names and parameters from the package spec. You can change the implementation details inside the package body without affecting the calling applications. Packages are stored in the database, where they can be shared by many applications. Calling a packaged subprogram for the first time loads the whole package and caches it in memory, saving on disk I/O for subsequent calls. Thus, packages enhance reuse and improve performance in a multi-user, multi-application environment.
  • Alternatively, you can also use a cursor FOR loops. before the first fetch from an OPEN cursor. Returns FALSE if the last fetch failed to return a row. • cursor_name%ISOPEN: Returns TRUE if the cursor is open, otherwise returns FALSE. • cursor_name%NOTFOUND: Returns FALSE if the last fetch returned a row. Returns NULL before the first fetch from an OPEN cursor. Returns TRUE if the last fetch failed to return a row. • cursor_name%ROWCOUNT: Returns zero before the first fetch. After every fetch returns the number of rows fetched so far.
  • L9 l10 server side programming

    1. 1. Database SystemsDatabase Systems 1 Server side DatabaseServer side Database Programming using PL/SQLProgramming using PL/SQL Version 1.1Version 1.1
    2. 2. 2
    3. 3. What is PL/SQL?  SQL Structured language to access database ANSI Standard Declarative ○ Specifies what to access but not how to - SELECT id, first_name, family_name FROM authors  PL/SQL Developed by Oracle as a procedural extension to SQL Declare variables, IF..ELSE, WHILE & FOR loops, functions, procedures and other features found in a programming language 3
    4. 4. Server Side Programming  PL/SQL executes inside DBMS DBMS maintains Relational data Also stores and executes Procedural code! Advantages Results from one query can be used as a basis for the next query without having to pull data from DBMS to client side for processing! 4
    5. 5. Client Side Procedural logic  DBMS maintains relational data  Client side programs implement procedural logic Is there a problem?  Performance impact due increased network traffic  Cumulative effect if many clients run at the same time  Code re-use may not be possible  Many applications may incorporate processing that are quite similar but sharing may not be easy! 5
    6. 6. PL/SQL - Basics  Block structured Basic program unit is a block Contains variables, code and error handler  A BLOCK is contained within BEGIN and END statements with executable commands in between Must contain some commands, even if they do nothing!  PL/SQL programs must at least contain 1 block  Blocks can be nested (block within another block) 6
    7. 7. PL/SQL – Block Syntax DECLARE variable declarations BEGIN program code EXCEPTION exception handler code END; 7 Optional
    8. 8. PL/SQL - EXCEPTIONs  EXCEPTIONS “unexpected errors” that occur during execution occurs at run-time not at compile time!  EXCEPTION HANDLER Code that executes when EXCEPTION occurs Makes the code more robust  Oracle Server has many pre-defined errors no_data_found, value_error, too_many_rows, others 8
    9. 9. PL/SQL - Anonymous Block DECLARE today date; BEGIN SELECT sysdate INTO today FROM dual; DBMS_OUTPUT.PUT_LINE (‘Today -’ || today); END; • What exactly happens in this code? • What is DUAL? (revision test !) 9
    10. 10. PL/SQL - Named Block  Has a name and stored in Oracle Server  Contains Header section name, key word - a function, procedure or trigger type of value it returns in case of function  At the time of creation, the code within the named block is NOT executed but compiled and stored in Oracle Server 10
    11. 11. PL/SQL - Data type - Character DECLARE family_name VARCHAR2 (20); Age NUMBER(3);  Assignment family_name := ‘Anderson’; Age := 21; 11
    12. 12. PL/SQL – %Type  %TYPE To map a variable directly to the same datatype as the table column DECLARE author_id AUTHORS.ID%TYPE;  PL/SQL variable ‘author_id’ is of same datatype which is used to define column name ‘id’ of table AUTHORS.  If column type changes PL/SQL Code would still work! {Example: VARCHAR2(20) to VARCHAR(30)} 12
    13. 13. PL/SQL - Scope Rules  Variables, procedures and functions can be referenced by the code executing inside the block in which they are defined  Understanding of scope of variables, functions is especially important in the context of nested blocks! 13
    14. 14. PL/SQL Scope Example DECLARE father_name VARCHAR2(20):='Patrick'; date_of_birth DATE:='20-Apr-1972'; BEGIN DECLARE child_name VARCHAR2(20):='Mike'; date_of_birth DATE:='12-Dec-2002'; BEGIN DBMS_OUTPUT.PUT_LINE('Father''s Name: '|| father_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: '|| date_of_birth); DBMS_OUTPUT.PUT_LINE('Child''s Name: '|| child_name); END; DBMS_OUTPUT.PUT_LINE('Date of Birth: '|| date_of_birth); END; / 14
    15. 15. PL/SQL Operators  Expressions consist of PL/SQL operators and operands Arithmetic Operators ○ **, *, /, +, - Comparison Operators ○ =, <>, !=, <, >, <=, >=, LIKE, BETWEEN, IN, IS NULL Logical Operators ○ AND, OR, NOT  String Operator – Concatenation using ‘||’ 15
    16. 16. PL/SQL – NULL  NULL means “UNKNOWN” value  Use IS NULL or IS NOT NULL to check for NULL value  NULL value comparison with ‘= NULL’ or ‘!= NULL’ may produce unpredictable results!  Use NVL function when appropriate NVL (<expression>, <value if expression is NULL>) 16
    17. 17. PL/SQL – SELECT sample DECLARE name VARCHAR2(20); surname VARCHAR2(20); BEGIN SELECT first_name, family_name INTO name, surname FROM AUTHORS WHERE id = 1 ; DBMS_OUTPUT.PUT_LINE (‘Row selected is : ‘ || name || ‘-’ || surname); END; 17
    18. 18. Performing DML Operations from PL/SQL (INSERT, UPDATE, and DELETE)  You can write INSERT, UPDATE, and DELETE statements directly in PL/SQL programs, without any special notation:  %ROWCOUNT Attribute: How Many Rows Affected So Far?  Example SET SERVEROUTPUT ON; BEGIN UPDATE employees SET salary = salary * 1.05 WHERE ...; dbms_output.put_line('Updated ' || SQL%ROWCOUNT || ' salaries.'); END; / 18
    19. 19. PL/SQL – Program Flow Control  Conditional execution IF-THEN, IF-THEN-ELSE, IF-THEN-ELSIF CASE  Repeated execution until some condition  LOOP-END LOOP, FOR-LOOP-END LOOP WHILE-LOOP-END LOOP EXIT WHEN  Jump to code section GOTO 19
    20. 20. PL/SQL – Conditional Execution IF <condition> THEN statement1; statement2; ….. END IF;  can be evaluated to TRUE, FALSE or NULL – statement1, statement2 etc., are executed only if it evaluates to TRUE 20
    21. 21. IF Example IF sales > quota THEN compute_bonus(empid); UPDATE payroll SET pay = pay + bonus WHERE empno = emp_id; END IF; 21
    22. 22. PL/SQL – IF-THEN-ELSE IF <condition> THEN statement1; statement2; ….. ELSE statement3; statement4; ….. END IF; 22
    23. 23. PL/SQL IF-THEN-ELSIF IF <condition1> THEN statement1; ….. ELSIF <condition2> statement3; …… ELSE ….. END IF; 23
    24. 24. Example BEGIN ... IF sales > 50000 THEN bonus := 1500; ELSIF sales > 35000 THEN bonus := 500; ELSE bonus := 100; END IF; INSERT INTO payroll VALUES (emp_id, bonus, ...); END; 24
    25. 25. 25
    26. 26. PL/SQL – Simple Loop  The EXIT-WHEN statement lets you complete a loop if further processing is impossible or undesirable.  When the EXIT statement is encountered, the condition in the WHEN clause is evaluated.  If the condition is true, the loop completes and control passes to the next statement.E.G. LOOP statement1; …… EXIT {WHEN ….} ; END LOOP; 26
    27. 27. PL/SQL LOOP Example  In the following example, the loop completes when the value of total exceeds 25,000: LOOP ... total := total + salary; EXIT WHEN total > 25000; -- exit loop if condition is true END LOOP; 27
    28. 28. PL/SQL – FOR LOOP FOR counter IN number1..number2 LOOP statement1; …… END LOOP; FOR counter IN REVERSE number1..number2 28
    29. 29. PL/SQL – FOR LOOP Example FOR i IN 1..3 LOOP -- assign the values 1,2,3 to i sequence_of_statements -- executes three times END LOOP; 29
    30. 30. PL/SQL – WHILE LOOP WHILE <condition> LOOP statement1; ….. END LOOP; 30
    31. 31. Pre-defined Errors - examples  NO_DATA_FOUND A SELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an index-by table.  TOO_MANY_ROWS A SELECT INTO statement returns more than one row.  ZERO_DIVIDE A program attempts to divide a number by zero. 31
    32. 32. PL/SQL Error Handling example DECLARE comm_missing EXCEPTION; -- declare own exception name VARCHAR2(20); surname VARCHAR2(20); BEGIN SELECT first_name, family_name INTO name, surname FROM AUTHORS; IF commission IS NULL THEN RAISE comm_missing; -- raise exception END IF; bonus := (salary * 0.10) + (commission * 0.15); EXCEPTION WHEN comm_missing THEN DBMS_OUPUT.PUT_LINE(‘Sorry cannot calculate bonus as there is no commission’); WHEN TOO_MANY_ROWS THEN DBMS_OUPUT.PUT_LINE(‘To much information to store ‘); END; / 32
    33. 33. Subprograms  An ideal way of writing Writing Reusable PL/SQL Code  PL/SQL has two types of subprograms called procedures and functions, which can take parameters and be invoked (called).  a subprogram is like a miniature program, beginning with a header followed by an optional declarative part, an executable part, and an optional exception-handling part: 33
    34. 34. Procedure Example PROCEDURE award_bonus (emp_id NUMBER) IS bonus REAL; comm_missing EXCEPTION; BEGIN -- executable part starts here SELECT comm * 0.15 INTO bonus FROM emp WHERE empno = emp_id; IF bonus IS NULL THEN RAISE comm_missing; ELSE UPDATE payroll SET pay = pay + bonus WHERE empno = emp_id; END IF; EXCEPTION -- exception-handling part starts here WHEN comm_missing THEN ... END award_bonus; . . . 34
    35. 35. Function Example CREATE OR REPLACE FUNCTION square( original NUMBER) RETURN NUMBER AS original_squared NUMBER; BEGIN original_squared := original * original; RETURN original_squared; END; / 35
    36. 36. Packages  PL/SQL lets you bundle logically related types, variables, cursors, and subprograms into a package  The packages defines a simple, clear, interface to a set of related procedures and types.  Packages usually have two parts: a specification and a body.  The specification defines the application programming interface; it declares the types, constants, variables, exceptions, cursors, and subprograms.  The body fills in the SQL queries for cursors and the code for subprograms. 36
    37. 37. Packages Example 37
    38. 38. Database Triggers  A database trigger is a stored subprogram associated with a database table, view, or event.  The trigger can be called once, when some event occurs, or many times, once for each row affected by an INSERT, UPDATE, or DELETE statement.  The trigger can be called after the event, to record it or take some followup action. Or, the trigger can be called before the event to prevent erroneous operations or fix new data so that it conforms to business rules. 38
    39. 39. Triggers Example CREATE TRIGGER audit_sal AFTER UPDATE OF sal ON emp FOR EACH ROW BEGIN INSERT INTO emp_audit VALUES ... END; 39
    40. 40. Cursors  A cursor is a pointer to the private memory area allocated by the Oracle server.  There are two types of cursors: Implicit cursors: Created and managed internally by the Oracle server to process SQL statements Explicit cursors: Explicitly declared by the programmer 40
    41. 41. Processing Explicit Cursors  The following three commands are used to process an explicit cursor: ○ OPEN ○ FETCH ○ CLOSE  Every explicit cursor has the following four attributes: ○ cursor_name%FOUND ○ cursor_name%ISOPEN ○ cursor_name%NOTFOUND ○ cursor_name%ROWCOUNT 41
    42. 42. Cursor Example 42

    ×