working with db2 data using sql and xquery

Upload: girish-kumar-nistala

Post on 08-Apr-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    1/16

    1

    IBM DB2 9

    2008 IBM Corporation

    Section -4) Working with DB2 DataWorking with DB2 Datausing SQL and XQueryusing SQL and XQuery

    IBM DB2 9

    2

    Section 4Section 4 -- Working with DB2 Data usingWorking with DB2 Data using

    SQL and XQuery (23.5%)SQL and XQuery (23.5%) Given a DML SQL statement, ability to identify resultsGiven a DML SQL statement, ability to identify results

    Ability to use SQL to SELECT data from tablesAbility to use SQL to SELECT data from tables

    Ability to use SQL to SORT or GROUP dataAbility to use SQL to SORT or GROUP data

    Ability to use SQL to INSERT, UPDATE, or DELETE dataAbility to use SQL to INSERT, UPDATE, or DELETE data

    Knowledge of transactions (i.e., COMMIT, ROLLBACK,Knowledge of transactions (i.e., COMMIT, ROLLBACK,

    and transaction boundaries)and transaction boundaries)

    Ability to call a procedure or invoke a user definedAbility to call a procedure or invoke a user defined

    functionfunction

    Given an XQuery statement, knowledge to identify resultsGiven an XQuery statement, knowledge to identify results

    IBM DB2 9

    3

    What is (Structured Query Language) SQL?

    Standard language of relational database access is SQL.Designed to access tabular data.

    Invented by IBM in the 1970s, the SQL language continues toevolve and is the only way to access relational database data.

    Three major categories.

    - DDL (Data Definition Language) - Used to create, modify,or drop database objects

    - DML (Data Manipulation Language) - Used to select, insert,update, or delete database data (records)

    - DCL (Data Control Language) - Used to provide data objectaccess control

    IBM DB2 9

    4

    Managing Database Objects - DDL

    To create, modify, delete objects in a database, SQL DataDefinition Language (DDL) is used.

    DDL has four basic SQL statements:

    - CREATE

    To create objects in a database.

    - DECLARE

    To create Temporary Tables in a database.

    - ALTER

    To make permitted alteration in structure of an object.

    - DROP

    To remove any object created with CREATE/ DECLAREstatements from database.

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    2/16

    2

    IBM DB2 9

    5

    Manipulate Data - DML

    To retrieve, insert, update or delete from tables and/or views,SQL Data Manipulation Language (DML) is used.

    DML also has four basic SQL statements:

    - SELECT

    To retrieve data from table or view.

    - INSERT

    To add records in tables.

    - UPDATE

    To change data.

    - DELETE

    To delete records from tables.

    IBM DB2 9

    6

    Using SELECT to Retrieve Data

    The SELECT statement is used to retrieve table orview data.

    Syntax -

    - SELECT [DISTINCT] columns

    - FROM TABLE(S)

    - WHERE condition

    - GROUP BY column

    - HAVING condition

    - ORDER BY column

    IBM DB2 9

    7

    Examples -

    SELECT * FROM staff;

    SELECT * FROM staff

    FETCH FIRST 10 ROWS ONLY;

    SELECT name, salary

    FROM staff;

    SELECT DISTINCT dept, job

    FROM staff;

    SELECT name, salary + comm AS pay

    FROM staff;

    IBM DB2 9

    8

    Question For You

    Given the following Query:

    SELECT last_name, first_name, age, hire_date

    FROM employee WHERE age > 40

    What will be the command:

    To return the rows sorted by AGE, oldest first, and by

    LAST_NAME, from A to Z

    Answer: ORDER BY age DESC, last_name

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    3/16

    3

    IBM DB2 9

    9

    CASE Expressions In SELECT

    SELECT empno, lastname, job, salary,

    CASE WHEN job IN ('MANAGER, ADMIN)

    THEN salary * 1.10

    WHEN job IN ('DBA, ARCHITECT)

    THEN salary * 1.08

    WHEN job = 'PROGRAMMER'

    THEN salary * 1.05

    ELSE salary * 1.035

    END as new_salary

    FROM employee

    IBM DB2 9

    10

    ExampleSELECT quantity,CASE WHEN itemcode = '099' THEN 'SILVER'WHEN itemcode = '788' THEN 'GOLD'WHEN itemcode = '899' THEN 'PLATINUM'ELSE 'ERROR'ENDFROM supplier

    Query:SUPPLIER------------------------------------------QUANTITY ITEMCODE

    3 0994 0991 7881 899

    5 0093 7881 899

    Output3,SILVER4,SILVER

    1,PLATINUM1,ERROR5,SILVER3,GOLD

    1,PLATINUM

    IBM DB2 9

    11

    With WHERE clause

    Use the WHERE clause to select specific rows from a table or

    view.

    Relational operators including:

    =, >, =,

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    4/164

    IBM DB2 9

    13

    Using Set Operators to Combine Multiple Queries

    With DB2, it is possible to combine two or more queries into asingle query by using a special operator known as a setoperator. When a set operator is used, the results of eachquery executed are combined in a specific manner to producea single result data set

    UNION - the result data sets produced by each individual queryare combined and all duplicate rows are eliminated

    INTERSECT - common records that are found in both the result

    data sets will be shown as final result set.EXCEPT - all records found in the first result data set that do

    not have a corresponding record in the second result data setwill be shown as final result set.

    IBM DB2 9

    14

    SELECT lastname, hiredate FROM employee

    WHEREMONTHNAME(hiredate) = 'December' AND

    salaryNOT BETWEEN 20000.00 AND 90000.00

    SELECT * FROM emp_exp_02 UNION

    SELECT * FROM emp_exp_01

    SELECT empno, lastname FROM employee

    WHERE lastname LIKE 'S%' ORDER BY empno

    SELECT COUNT(*) FROM employee WHERE

    workdept IN (SELECT deptno FROM department

    WHERE admrdept = 'A00')

    SELECT workdept, DECIMAL(AVG(salary), 9, 2)

    AS avg_salary FROM employee GROUP BY work

    dept HAVINGAVG(salary) > 60000

    IBM DB2 9

    15

    Using Joins - Concepts

    A join combines data from two or more tables. A joincondition is required to refine the result set (eliminates acartesian product). Joining can be INNER or OUTER.

    INNER JOIN - Keeps only the rows from the cross productthat meet the join condition. If a row exists in both the tablesthen only they will be included in the result set.

    OUTER JOIN is a concatenation of the inner join and rowsfrom the left table, right table, or both tables that are missingfrom the inner join. There are 3 types of Outer Join.

    1. Left outer join = inner join + rows from the left table

    2. Right outer join = inner join + rows from the right table

    3. Full outer join = inner join + the rows from both the tables

    IBM DB2 9

    16

    Using Joins Examples

    SELECT lastname, deptname FROM employee e,

    department d WHERE e.workdept = d.deptno

    OR

    SELECT lastname, deptname FROM employee e INNER

    JOIN department d ON e.workdept = d.deptnoSELECT lastname, deptname FROM employee e LEFT

    OUTER JOIN department d ON e.workdept = d.deptno

    SELECT lastname, deptname FROM employee e RIGHT

    OUTER JOIN department d ON e.workdept = d.deptno

    SELECT lastname, deptname FROM employee e FULL

    OUTER JOIN department d ON e.workdept = d.deptno

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    5/165

    IBM DB2 9

    17

    IBM DB2 9

    18

    IBM DB2 9

    19

    IBM DB2 9

    20

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    6/166

    IBM DB2 9

    21

    INSERT Statement

    The INSERT statement is used to add new rows to atable or a view.

    Examples:

    INSERT INTO staff VALUES

    (1212,'Cerny',NULL,'Sales',3)

    INSERT INTO staff (id, name, dept, job, years)

    VALUES (1212,'Cerny',20,'Sales',3),

    (1213,'Wolfrum',20,NULL,2)

    INSERT INTO department (deptno, deptname)

    SELECT deptno, deptname FROM sales_depts

    IBM DB2 9

    22

    Example of inserting values in Table using

    values of other Table Given the following two tables:

    TAB1

    C1 C2 __ __________1 Antarctica

    2 Africa3 Asia4 Australia

    TAB2

    CX CY---- ---------5 Europe

    6 North America7 South America

    Query:Insert all rows found in table TAB2into table TAB1.

    Command:INSERT INTO tab1 SELECT cx, cy

    FROM tab2

    IBM DB2 9

    23

    UPDATE Statement

    The UPDATE statement is used to change the data in

    a table or a view.

    For example:

    UPDATE staff SET dept = NULL

    WHERE ename LIKE A%

    UPDATE staff SET (dept, sal)=(51, 7000)

    WHERE id = 750

    UPDATE employees SET (dept) =

    (SELECT deptname FROM department

    WHERE deptno = 1)

    IBM DB2 9

    24

    DELETE Statement

    The DELETE statement is used to delete entire rows

    of data from a table.

    For example:

    DELETE FROM staff WHERE id IN (1212, 1213)

    DELETE FROM sales WHERE salesperson IS NULL

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    7/167

    IBM DB2 9

    25

    IBM DB2 9

    26

    The COMMIT and ROLLBACK statements

    A unit of work (UOW), also known as a transaction, is arecoverablesequence of operations within an applicationprocess. Ex. transfer funds transaction.

    The application ends the UOW by issuing either a COMMIT ora ROLLBACK statement, whichever is appropriate.

    The COMMIT statement makes all changes made within the

    UOW permanent, whereas the ROLLBACK statement reversesthose changes.

    If the application ends normally without an explicit COMMIT orROLLBACK statement, the UOW is automatically committed.

    If the application ends abnormally before the end of a UOW,that unit of work is automatically rolled back.

    IBM DB2 9

    27

    Savepoints

    A savepoint lets you selectively roll back a subset of actions

    that make up a UOW without losing the entire transaction.

    do some work;

    savepoint A;

    do some more work;

    savepoint B;

    do even more work;

    savepoint C;

    wrap it up;

    roll back to savepoint B;

    IBM DB2 9

    28

    Invoking User-Defined Functions

    CREATE FUNCTION jobemployees (job VARCHAR(8))

    RETURNS TABLE (empno CHAR(6),

    firstname VARCHAR(12), lastname VARCHAR(15))

    LANGUAGE SQL READS SQL DATA

    NO EXTERNAL ACTION DETERMINISTICRETURN SELECT empno, firstnme, lastname

    FROM employee

    WHERE employee.job = jobemployees.job;

    Calling function -

    SELECT * FROM TABLE (jobemployees('CLERK'))

    SELECT temp AS tempf, convert_temp(temp, 'F') AS tempcFROM climate_info

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    8/168

    IBM DB2 9

    29

    Calling a Stored Procedure

    CREATE PROCEDURE get_sales(IN quota INTEGER, OUT retcode CHAR(5))DYNAMIC RESULT SETS 1 LANGUAGE SQL

    BEGIN

    DECLARE sqlstate CHAR(5);DECLARE sales_results CURSOR WITH RETURN FORSELECT sales_person, SUM(sales) AS total_sales

    FROM sales GROUP BY sales_personHAVING SUM(sales) > quota;

    DECLARE EXIT HANDLER FOR SQLEXCEPTIONSET retcode = sqlstate; OPEN sales_results;SET retcode = sqlstate;

    END

    CALL get_sales (25, ?)

    IBM DB2 9

    30

    What is XML?

    XML was designed to structure, store and to senddata/information.

    At its core XML is text formatted in the form of tags and textthat follow a well-defined set of rules.

    This text may be stored/represented in:

    - A normal file stored on disk

    - A message being sent over HTTP

    - A character string in a programming language

    -A CLOB (character large object) in a database

    - Any other way textual data can be used

    John Smith Co

    1234 W. Main StToledoOH95141

    A5412

    9851

    IBM DB2 9

    31

    IBM DB2 9

    32

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    9/169

    IBM DB2 9

    33

    IBM DB2 9

    34

    XML specifications

    XMLdocument

    s

    XSD

    XQuery XPathXSLT

    DTDdescribes

    describes

    searches searches transforms

    uses

    uses

    uses

    uses

    supersedes

    IBM DB2 9

    35

    IBM DB2 9

    36

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    10/1610

    IBM DB2 9

    37

    XPath Expressions

    IBM DB2 9

    38

    IBM DB2 9

    39

    IBM DB2 9

    40

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    11/1611

    IBM DB2 9

    41

    IBM DB2 9

    42

    IBM DB2 9

    43

    IBM DB2 9

    44

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    12/1612

    IBM DB2 9

    45

    IBM DB2 9

    46

    XML Facilities XML data type for columns

    -create s1.t1 (c1 int, c2 xml)

    Language bindings for XML type in programming languages

    - cobol, c, java, etc..

    XML indexes

    - create ix1 on s1.t1(c2) generate keys using pattern /dept/emp/@empno

    An XML schema/DTD repository

    Support for XQuery as a primary language as well as:

    - Support for SQL within XQuery

    -Support for XQuery with SQL

    - Support for new SQL/XML functions

    Performance, scale, and everything else they expect from a

    DBMS

    IBM DB2 9

    47

    Two ways to query XML data in DB2

    Using XQuery as the primary language

    - All queries begin with XQuery.

    - Tells the DB2 parser what to expect

    -Can execute SQL within a query beginning with XQUERY

    Using SQL as the primary language

    - Part 2

    IBM DB2 9

    48

    XQuery: The FLWOR Expression

    FOR: iterates through a sequence, bind variable to items LET: binds a variable to a sequence WHERE: eliminates items of the iteration ORDER: reorders items of the iteration RETURN: constructs query results

    create table dept(deptID char(8), deptdoc xml);

    xquery

    for $d in db2-fn:xmlcolumn(dept.deptdoc)/dept

    let $emp := $d//employee/name

    where $d/@bldg > 95

    order by $d/@bldg

    return

    {$d/@bldg, $emp}

    John Doe

    408 555 1212

    344

    Peter Pan

    408 555 9918

    216

    Input:

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    13/16

    13

    IBM DB2 9

    49

    John DoePeter Pan

    John DoePeter Pan

    FLWOR Expression

    John DoePeter Pan

    xquery

    for $d in xmlcolumn(deptdoc)/dept

    where $d/@bldg = 101

    return

    {$d/employee/name}

    This result is not an XML document!

    xquery

    for $d in xmlcolumn(deptdoc)/dept

    where $d/@bldg = 101return $d/employee/name/text()

    xquery

    for $d in xmlcolumn(deptdoc)/dept

    where $d/@bldg = 101

    return $d/employee/name

    John Doe

    408 555 1212

    344

    Peter Pan

    408 555 9918

    216

    create table dept (deptID char(8), deptdoc xml);

    IBM DB2 9

    50

    Two ways to query XML data in DB2

    Using XQuery as the primary language- Done

    Using SQL as the primary language

    - Looking at query only

    - All queries begin with Select

    - XML Retrieval done with XMLQUERY (flags db2 parser to

    switch to XML Processing)

    IBM DB2 9

    51

    XML Functions

    XMLQUERY(). function that enables you to execute an XQueryexpression from within an SQL context. It returns an XMLvalue, which is an XML sequence. This sequence can beempty or it can contain one or more items.

    XMLTABLE(). returns a table from the evaluation of XQueryexpressions; XQuery expressions normally return values as asequence, however, XMLTABLE() allows you to execute anXQuery expression and return values as a table instead.

    XMLEXISTS(). If it returns an empty sequence, XMLEXISTSreturns FALSE; otherwise, TRUE is returned. The XMLEXISTSpredicate can be used in the WHERE clauses of UPDATE,DELETE, and SELECT statements.

    IBM DB2 9

    52

    DML statements for XML Data

    INSERT INTO customers (custinfo) VALUES (

    XMLPARSE(DOCUMENT 'John Doe'PRESERVE WHITESPACE))

    DELETE FROM customer WHERE XMLEXISTS ('declare

    default element namespace "http://custrecord.dat";$info/customerinfo[name/text()=" John Doe"]'

    PASSING custinfo AS "info")

    UPDATE customerSET custinfo = XMLPARSE (DOCUMENT Jane

    Doe PRESERVE WHITESPACE)WHERE empno = 11;

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    14/16

    14

    IBM DB2 9

    53

    XMLTABLE - XML to relational

    95023USnull4711

    33129USBobby1325

    ZipZipTypeNameCID

    SELECT X.* fromXMLTABLE (db2-fn:xmlcolumn(PORDERS.PO)//customerCOLUMNSCID INTEGER PATH @id,Name VARCHAR(30) PATH name,ZipType CHAR(2) PATH zip/@type,Zip XML PATH zip) AS X

    IBM DB2 9

    54

    IBM DB2 9

    55

    Given the following queries:

    SELECT c1 FROM tab1; SELECT c1 FROM tab2;

    Which of the following set operators can be used to

    produce a result data set that contains only records

    that are not found in the result data set produced by

    each query after duplicate rows have beeneliminated?

    A. UNION

    B. INTERSECT

    C. EXCEPT

    D. MERGE

    IBM DB2 9

    56

    Given the following UPDATE statement:

    UPDATE employees SET workdept = (SELECT deptno FROMdepartment WHERE deptno = 'A01') WHERE workdept IS NULL

    Which of the following describes the result if this statement is

    executed?

    A. The statement will fail because an UPDATE statement cannot

    contain a subquery. B. The statement will only succeed if the data retrieved by the

    subquery does not contain multiple records.

    C. The statement will succeed; if the data retrieved by the subquery

    contains multiple records, only the first record will be used to perform

    the update.

    D. The statement will only succeed if every record in theEMPLOYEES table has a null value in the WORKDEPT column.

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    15/16

  • 8/6/2019 Working With DB2 Data Using SQL and XQuery

    16/16

    16

    IBM DB2 9

    61

    A stored procedure has been created with the

    following statement:CREATE PROCEDURE proc1 (INvar1 VARCHAR(10), OUT rc INTEGER) SPECIFICmyproc LANGUAGE SQL What is the correct way

    to invoke this procedure from the command line

    processor (CLP)?

    A. CALL proc1 ('SALES', ?)

    B. CALL myproc ('SALES', ?)

    C. CALL proc1 (SALES, ?)D. RUN proc1 (SALES, ?)

    IBM DB2 9

    62

    Japanese

    Hebrew

    Thank

    YouEnglish

    MerciFrench

    Russian

    DankeGerman

    GrazieItalian

    GraciasSpanish

    ObrigadoPortuguese

    Arabic

    Simplified Chinese

    Traditional Chinese

    Tamil

    Thai

    Korean