Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL PL/SQL Presented by: Dr. Samir Tartir

Similar presentations


Presentation on theme: "SQL PL/SQL Presented by: Dr. Samir Tartir"— Presentation transcript:

1 SQL PL/SQL Presented by: Dr. Samir Tartir
Session - 6 Sequence – 7 SQL PL/SQL Presented by: Dr. Samir Tartir

2 Outline Goals Types Structure

3 PL/SQL PL/SQL (Procedural Language/Structured Query Language) is Oracle's procedural extension language for SQL and the Oracle relational database. PL/SQL's general syntax resembles that of Ada. PL/SQL supports variables, conditions, loops and exceptions. PL/SQL blocks can include control flow and DML statements.

4 Benefits of Server-Side Code
Can be used to include the business logic directly in the database. Code can be shared for all database users. Smaller network traffic, since code and data reside in the same location.

5 When is PL/SQL Useful? When something is too complicated for SQL
When conditional branching and looping are needed

6 Types Runtime Code Stored Procedures Stored Functions Stored Packages
Triggers 6

7 Basic Structure [DECLARE ... Local variables ]  Optional BEGIN ... PL/SQL Code [EXCEPTION ... Handlers]  Optional END; 7

8 Comments Single Line Multiple lines
Anything in the line after the “--” is ignored -- …comment E.g: sal integer; -- store salary Multiple lines Anything between “/*” and “*/” is ignored. /* …comment… */ sal integer; /* this is A Multiline Comment */

9 Variables Variables can have: Examples:
any SQL data type, such as CHAR, DATE, or NUMBER or any PL/SQL data type, such as BOOLEAN or BINARY_INTEGER. Examples: part_no NUMBER(4); in_stock BOOLEAN; 9

10 Assigning Values to Variables
Using the assignment operator (:=) E.g.: tax := price * tax_rate; Selecting database values into it SELECT salary * 0.10 INTO bonus FROM employee WHERE SSN = SSN_In; Passing it as an OUT or IN OUT parameter when calling a procedure adjust_salary(7788, my_sal); 10

11 Flow Control – If Statement
IF acct_balance >= debit_amt THEN UPDATE accounts SET bal = bal - debit_amt WHERE account_id = acct; ELSE INSERT INTO temp VALUES (acct, acct_balance, 'Insufficient funds'); END IF; 11

12 Flow Control – Case Statement
CASE WHEN shape = 'square' THEN area := side * side; WHEN shape = 'circle' THEN BEGIN area := pi * (radius * radius); END; WHEN shape = 'rectangle' THEN area := length * width; ELSE DBMS_OUTPUT.PUT_LINE('No formula'); RAISE PROGRAM_ERROR; END CASE; 12

13 For Loops It lets you specify a range of integers, then execute a sequence of statements once for each integer in the range. FOR num IN LOOP INSERT INTO roots VALUES (num, SQRT(num)); END LOOP; 13

14 While Loops Associates a condition with a sequence of statements.
Before each iteration of the loop, the condition is evaluated. If the condition is true, the sequence of statements is executed, then control resumes at the top of the loop. If the condition is false or null, the loop is bypassed and control passes to the next statement. 14

15 Example WHILE salary <= 2500 LOOP SELECT salary, mgr_ssn, lname INTO salary, mgr_ssn, last_name FROM employee WHERE ssn = mgr_ssn; END LOOP; 15

16 Cursors A cursor is a pointer to a private SQL area that stores results of a SELECT statement Example: DECLARE CURSOR c1 IS SELECT empno, ename, job FROM emp WHERE deptno = 20; 16

17 Cursors Operations OPEN FETCH CLOSE 17

18 Cursor Variables cursorname%ROWCOUNT Rows returned so far
cursorname%FOUND One or more rows retrieved cursorname%NOTFOUND No rows found Cursorname%ISOPEN Is the cursor open 18

19 Example – Using a For Loop
SET SERVEROUTPUT ON DECLARE CURSOR c1 is SELECT fname, ssn, salary FROM employee ORDER BY salary DESC; --start w/ highest paid emp my_ename VARCHAR2(10); my_empno CHAR(9); my_sal NUMBER(10,2); BEGIN OPEN c1; FOR i IN 1..5 LOOP FETCH c1 INTO my_ename, my_empno, my_sal; EXIT WHEN c1%NOTFOUND; /* in case the number requested */ /* is more than the total */ /* number of employees */ DBMS_OUTPUT.PUT_LINE (MY_EMPNO||','||MY_SAL); END LOOP; CLOSE c1; END; /

20 Example – Using a While Loop
SET SERVEROUTPUT ON DECLARE CURSOR c1 is SELECT fname, ssn, salary FROM employee ORDER BY salary DESC; --start w/ highest paid emp my_ename VARCHAR2(10); my_empno CHAR(9); my_sal NUMBER(10,2); BEGIN OPEN c1; FETCH c1 INTO my_ename, my_empno, my_sal; WHILE C1%FOUND LOOP DBMS_OUTPUT.PUT_LINE (MY_EMPNO||','||MY_SAL); END LOOP; CLOSE c1; END; /

21 Exception Handling Here we define the actions that should happen when an exception is thrown. Example Exceptions: NO_DATA_FOUND TOO_MANY_ROWS ZERO_DIVIDE User-defined exceptions

22 Example DECLARE num_row number_table%ROWTYPE; BEGIN select *
into num_row from number_table; dbms_output.put_line(1/num_row.num); EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line('No data!'); WHEN TOO_MANY_ROWS THEN dbms_output.put_line('Too many!'); WHEN OTHERS THEN dbms_output.put_line(‘Error’); end;

23 Example Create a new table: Employee2 For each employee
Fname, LName, SSN, Salary, Salary2, Dsc For each employee If the employee worked more than 40 hours on all projects Put “Good” in his description and give him a 10% raise Otherwise: Put “Bad” in his description Find the employee with the highest salary and print his name and SSN Display the name and salary of employee with SSN “ ”. If no employee has that SSN, display “Employee not found”

24 SUMMARY Oracle uses PL/SQL to include business logic right in the database directly. PL/SQL has many PL features to facilitate code writing Code can be Procedures, functions, packages or triggers

25 Resources & References
Dr. Samir Tartir Website: Fundamentals of Database Systems by El Masri & Navathe. Publisher : Addison-Wesley, 5th edition, 2006.


Download ppt "SQL PL/SQL Presented by: Dr. Samir Tartir"

Similar presentations


Ads by Google