Your SlideShare is downloading. ×

SQl

1,031
views

Published on

Published in: Technology, Business

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,031
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
46
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. ICS 184: Introduction to Data Management Lecture Note 13: Stored Procedures and Embedded SQL
  • 2.
    • A function stored in the DB server
    • Can be invoked multiple times
    • Advantage: reduce network traffic
    • Can also be written using other languages
      • e.g., C, Java
    • Different vendors could have different implementations
      • Check the manual and sample programs
    Stored Procedures
  • 3. Architecture Client Application DB Client Normal Database Network DB Client Client Application DB Client Stored Procedures Applications using stored procedures Network DB Client DB Server DB DB Server DB
  • 4.
    • Allows local variables, loops, procedures, examination of one tuple at a time.
    • CREATE PROCEDURE <name> (<arglist>)
    • BEGIN
        • <procedure statements>
        • END
        • @
    • <Procedure Statements> can have multiple SQL statements
    • '@' needed for ending and running.
    • Each argument can be:
      • IN
      • OUT
      • INOUT
    Declare Stored Procedures (DB2 syntax)
  • 5.
    • CREATE TABLE emp(id INTEGER, salary FLOAT);
    • CREATE PROCEDURE
    • UPDATE_EMP (IN idNum INTEGER, IN rate FLOAT)
    • LANGUAGE SQL
    • BEGIN
    • UPDATE EMP
    • SET salary = salary* (1.0 + rate)
    • WHERE id = idNum;
    • END
    • @
    • Name: UPDATE_EMP.
    • The two parameters are of data type INTEGER and FLOAT. Both are input parameters.
    • LANGUAGE SQL indicates that this is an SQL procedure, so a procedure body follows the other parameters.
    • The procedure body consists of a single SQL UPDATE statement, which updates rows in the emp table.
    • '@' is used as the terminating character for stored procedures in DB2.
    Example
  • 6.
    • CALL UPDATE_EMP (2, 0.1);
    Call Stored Procedures CALL UPDATE_EMP (3, 0.2);
  • 7.
    • Call another procedure in a procedure (like calling functions)
    • To call a target SQL procedure within a caller SQL procedure, simply include a CALL statement with the appropriate number and types of parameters.
    • CREATE PROCEDURE NEST_SALES(OUT budget DECIMAL(11,2))
    • LANGUAGE SQL
    • BEGIN
    • DECLARE total INTEGER DEFAULT 0;
    • SET total = 6;
    • CALL SALES_TARGET(total);  call another procedure
    • SET budget = total * 10000;
    • END
    • @
    • “ budget” is an output variable
    Nested Procedures
  • 8.
    • CASE statement
    • FOR statement
    • GOTO statement
    • IF statement
    • ITERATE statement
    • RETURN statement
    • WHILE statement
    • Similar to other programming languages.
    Valid Body Statements
  • 9.
    • Conditional Statements
      • IF <condition> THEN
      • <statement(s)>
      • ELSE
      • <statement(s)>
      • END IF;
    • Loops
      • LOOP
      • ……
      • EXIT WHEN <condition>
      • ……
      • END LOOP;
    Example Statements
  • 10.
    • CREATE PROCEDURE UPDATE_SALARY_IF
    • (IN employee_number INT, IN rating SMALLINT)
    • LANGUAGE SQL
    • BEGIN
    • IF (rating = 1) THEN
        • BEGIN
        • DECLARE count INT;
    • SET counter = 10;
    • WHILE (counter > 0) DO
    • UPDATE employee
    • SET salary = salary * 1.10, bonus = 1000
    • WHERE empno = COUNT;
    • SET counter = counter – 1;
    • END WHILE;
    • END
    • ELSEIF (rating = 2)
    • THEN UPDATE employee
    • SET salary = salary * 1.05, bonus = 500
    • WHERE empno = employee_number;
    • ELSE UPDATE employee
    • SET salary = salary * 1.03, bonus = 0
    • WHERE empno = employee_number;
    • END IF;
    • END
    • @
    Example 1
  • 11.
    • CREATE PROCEDURE BUMP_SALARY_IF (IN deptnumber SMALLINT)
    • LANGUAGE SQL
    • BEGIN
    • DECLARE v_salary DOUBLE;
    • DECLARE v_years SMALLINT;
    • DECLARE v_id SMALLINT;
    • DECLARE at_end INT DEFAULT 0;
    • DECLARE not_found CONDITION FOR SQLSTATE '02000';  “not found” reached
    • -- CAST salary as DOUBLE because SQL procedures do not support DECIMAL
    • DECLARE C1 CURSOR FOR
    • SELECT id, CAST(salary AS DOUBLE), years
    • FROM staff;
    • DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1;
    Example 2
  • 12.
    • OPEN C1;
    • FETCH C1 INTO v_id, v_salary, v_years;
    • WHILE at_end = 0 DO
    • IF (v_salary < 2000 * v_years)
    • THEN UPDATE staff
    • SET salary = 2150 * v_years
    • WHERE id = v_id;
    • ELSEIF (v_salary < 5000 * v_years)
    • THEN IF (v_salary < 3000 * v_years)
    • THEN UPDATE staff
    • SET salary = 3000 * v_years
    • WHERE id = v_id;
    • ELSE UPDATE staff
    • SET salary = v_salary * 1.10
    • WHERE id = v_id;
    • END IF;
    • ELSE UPDATE staff
    • SET job = 'PREZ'
    • WHERE id = v_id;
    • END IF;
    • FETCH C1 INTO v_id, v_salary, v_years;
    • END WHILE;
    • CLOSE C1;
    • END
  • 13. Example 2: description
    • This procedure receives a department number as an input parameter.
    • A WHILE statement in the procedure body fetches the salary and bonus for each employee in the department.
    • An IF statement within the WHILE statement updates salaries for each employee, depending on number of years of service and current salary.
    • When all employee records in the department have been processed, the FETCH statement that retrieves employee records receives SQLSTATE 20000.
    • A not_found condition handler makes the search condition for the WHILE statement false, so execution of the WHILE statement ends
  • 14. Writing your stored procedures
    • Different vendors have implementations of stored procedures
    • As always:
      • Start from a sample program. Do not start from scratch!
      • “ Copy and paste”
  • 15. Embedded SQL
    • Direct SQL is rarely used
    • Usually, SQL is embedded in some application code.
    • Need some method to reference SQL statements
    Host language + Embedded SQL Preprocessor Host Language + function calls Host language compiler Host language program
    • The best way to do programming:
      • Start with a template
      • Modify the template to write your own program!
  • 16. The Impedance Mismatch Problem
    • The host language manipulates variables, values, pointers.
    • SQL manipulates relations.
    • No construct in host language for manipulating relations.
    • Why not use only one language?
      • Forgetting SQL  definitely not a good idea!
      • SQL cannot do everything that the host language can do.
    • Interface between SQL and host language:
      • Values get passed through shared variables.
      • Colons precede shared variables when occurring within SQL statements.
      • EXEC SQL: precedes every SQL statement in host language.
  • 17. Example Void simpleInsert() { EXEC SQL BEGIN DECLARE SECTION; char productName[20], company[30]; char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; /* get values for productName and company somehow */ EXEC SQL INSERT INTO Product(name, company) VALUES (:productName, :company); } Variable SQLSTATE provides error messages and status reports (e.g., 00000 means operation completed without problem).
  • 18. Single-Row Select Statements Void getPrice() { EXEC SQL BEGIN DECLARE SECTION; char productName[20], company[30]; integer price; char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; /* read value of product name */ EXEC SQL SELECT price INTO :price FROM Product WHERE Product.name = :productName; /* print out value of price */ }
  • 19. Cursors Motivation: go through the results of a query EXEC SQL DECLARE cursorName CURSOR FOR SELECT …. FROM …. WHERE …. ; EXEC SQL OPEN cursorName ; while (true) { EXEC SQL FETCH FROM cursorName INTO :variables; if ( NO_MORE_TUPLES ) break; /* do something with values */ } EXEC SQL CLOSE cursorName ;
  • 20. More on Cursors
    • Cursors can modify a relation as well as read it.
    • Order can be determined by ORDER BY keyword in SQL query.
    • Can be protected against changes to underlying relations.
    • Can scroll: go forward, backward, +n, -n, Abs(n), Abs(-n).