• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
SQl
 

SQl

on

  • 1,321 views

 

Statistics

Views

Total Views
1,321
Views on SlideShare
1,320
Embed Views
1

Actions

Likes
0
Downloads
44
Comments
0

1 Embed 1

http://www.slideshare.net 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    SQl SQl Presentation Transcript

    • ICS 184: Introduction to Data Management Lecture Note 13: Stored Procedures and Embedded SQL
      • 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
    • 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
      • 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)
      • 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
      • CALL UPDATE_EMP (2, 0.1);
      Call Stored Procedures CALL UPDATE_EMP (3, 0.2);
      • 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
      • CASE statement
      • FOR statement
      • GOTO statement
      • IF statement
      • ITERATE statement
      • RETURN statement
      • WHILE statement
      • Similar to other programming languages.
      Valid Body Statements
      • Conditional Statements
        • IF <condition> THEN
        • <statement(s)>
        • ELSE
        • <statement(s)>
        • END IF;
      • Loops
        • LOOP
        • ……
        • EXIT WHEN <condition>
        • ……
        • END LOOP;
      Example Statements
      • 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
      • 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
      • 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
    • 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
    • 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”
    • 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!
    • 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.
    • 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).
    • 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 */ }
    • 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 ;
    • 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).