db2 high level queries

16
SPECIAL SQL FEATURES

Upload: jagan-yalla

Post on 16-Dec-2015

225 views

Category:

Documents


5 download

DESCRIPTION

db2 , high level queries,

TRANSCRIPT

  • SPECIAL SQL FEATURES

  • Merge statement is a combination of delete, insert and update. Merge statement can update a table or a view from source table during single operation. If row in a target table matches with source table based on condition , then same row can be updated or deleted.If row in a source table does not match target table , it can be inserted. Example: For example, consider the EMPLOYEE table to be the target table that contains up-to-date information about the employees of a large company. Branch offices handle updates to local employee records by maintaining their own version of the EMPLOYEE table called MY_EMP. The MERGE statement can be used to update the EMPLOYEE table with information that is contained in a MY_EMP table, which is the source table for the merge operation.INSERT INTO my_emp (empno, firstnme, midinit, lastname, workdept,phoneno, hiredate, job, edlevel, sex, birthdate, salary)VALUES ('000015', 'MARIO', 'M', 'MALFA', 'A00','6669', '05/05/2000', 'ANALYST', 15, 'M', '04/02/1973', 59000.00)

    Merge Statement

  • MERGE INTO employee AS e USING (SELECT empno, firstnme, midinit, lastname, workdept, phoneno,hiredate, job, edlevel, sex, birthdate, salaryFROM my_emp) AS m ON e.empno = m.empno WHEN MATCHED THEN UPDATE SET (salary) = (m.salary)WHEN NOT MATCHED THENINSERT (empno, firstnme, midinit, lastname, workdept, phoneno,hiredate, job, edlevel, sex, birthdate, salary)VALUES (m.empno, m.firstnme, m.midinit, m.lastname,m.workdept, m.phoneno, m.hiredate, m.job, m.edlevel,m.sex, m.birthdate, m.salary)MERGE STATEMENT EXAMPLE

  • A Special procedure in SYSPROC schema to run administrative commands directly from application or from another procedure. Cannot be called from functions and Triggers.ADMIN_CMD allows one parameter of size clob(2M) which should contain single administrative command. Most commonly used for DESCRIBE.EXPORTIMPORTREORG ON INDEX/TABLERUN STATSLOADFORCE APPLICATIONUPDATE DATABASE CONFIGURATION.SYSTEM PROC ADMIN_CMD

  • Example1:CALL SYSPROC.ADMIN_CMD(REORG TABLE TABLE_NAME);

    Example2:CALL SYSPROC.ADMIN_CMD(RUNSTATS ON TABLE TABLE_NAME WITH DISTRIBUTION AND DETAILED INDEX ALL);

    Example3:CREATE PROCEDURE test_admin_cmd ( )P1: BEGIN DECLARE sql_string VARCHAR(200); SET sql_string ='LOAD FROM C:\DB9.5_test\org_exp.txt OF DEL METHOD P (1, 2, 3, 4, 5) INSERT INTO DB2ADMIN.ORG1 (DEPTNUMB, DEPTNAME, MANAGER, DIVISION, LOCATION) COPY NO INDEXING MODE AUTOSELECT'; CALL SYSPROC.ADMIN_CMD(sql_string);END P1ADMIN_CMD EXAMPLES

  • It provides information of previously executed queries. It never changes the SQLCODE or SQLSTATE special variables.Its useful to get the 1. Number of records updated by the command.2. Status of last executed statement.3. Capturing the error message of last executed statement.Get diagnostics variables :DB2_RETURN_STATUSROW_COUNTMESSAGE_TEXTDB2_TOKEN_STRING

    GET DIAGNOSTICS

  • Example1:CREATE PROCEDURE UPDATE_RCOUNT(sales_corr INT, qtr int, OUT row_updated INT)P1: BEGIN UPDATE SALESBYQUARTER SET sales = sales+sales_corr WHERE y < year(current date) and q = qtr; GET DIAGNOSTICS row_updated = ROW_COUNT; END P1;GET DIAGNOSTICS EXAMPLES

  • Example2:CREATE PROCEDURE mess_text1 (num int, new_status varchar(10), OUT p_err_mess varchar(70))P1: BEGIN DECLARE SQLCODE INTEGER default 0; DECLARE SQLSTATE CHAR(5) default ''; DECLARE v_trunc int default 0; DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN GET DIAGNOSTICS EXCEPTION 1 p_err_mess = MESSAGE_TEXT; SET v_trunc = 2; END; INSERT INTO tab1 VALUES (num, new_status); RETURN v_trunc;END P1

  • CREATE PROCEDURE myproc1 () A1:BEGIN DECLARE RETVAL INTEGER DEFAULT 0; CALL MYPROC2(); GET DIAGNOSTICS RETVAL = DB2_RETURN_STATUS; IF RETVAL 0 THEN LEAVE A1; ELSE END IF; END A1

  • Save point provide a means of implementing a subtraction within a unit of work.Its possible to create a multiple save points with in a transaction which can be referred later.Commit destroys save point, Its highly suggestible to use commit at the end of the transaction.Its very easy to rollback to a save point without impacting any work prior to that save point.

    SYNTAX:

    SAVEPOINT savepoint-name ON ROLLBACK RETAIN CURSORS

    SAVE POINT

  • CREATE PROCEDURE p1()BEGIN CREATE TABLE T1 (C1 CHAR); INSERT INTO T1 VALUES ('A'); SAVEPOINT SAVEPOINT1 ON ROLLBACK RETAIN CURSORS; INSERT INTO T1 VALUES ('B'); SAVEPOINT SAVEPOINT2 ON ROLLBACK RETAIN CURSORS; INSERT INTO T1 VALUES ('C'); SAVEPOINT SAVEPOINT3 ON ROLLBACK RETAIN CURSORS; INSERT INTO T1 VALUES ('D'); ROLLBACK TO SAVEPOINT SAVEPOINT3; ROLLBACK TO SAVEPOINT SAVEPOINT1; COMMIT WORK; INSERT INTO T1 VALUES ('E');END@SAVE POINT EXAMPLE

  • Temporary tables are more often used to store temporary and intermediate results.It can only access by the connection in which it was declared or created.It is dropped when connection ended.

    It increase performance becauseIt does not require logging.Do not appear in system catalog tables.Do not require lock because it allows single connection access.

    GLOBAL DECLARED TEMPORARY TABLES

  • .-,---------------------. V |

    >--+-(----| column-definition |-+--)-----------------------------+--> +-LIKE--+-table-name1-+--+------------------+-----------------+ | '-view-name---' '-| copyoptions|-' | '-AS--(--fullselect--)--DEFINITION ONLY--+------------------+-' '-| copy-options |-' .-ON COMMIT DELETE ROWS---.>--?--+-------------------------+--?----------------------------> '-ON COMMIT PRESERVE ROWS-'>--+-------------------------------------------+----------------> | .-ON ROLLBACK DELETE ROWS---. | '-NOT LOGGED--+---------------------------+-' '-ON ROLLBACK PRESERVE ROWS-'>--?--+--------------+--?--+---------------------+--------------> '-WITH REPLACE-' '-IN--tablespace-name-'>--?--+------------------------------------------------------------+--?->< | .-,-----------. | | V | .-USING HASHING-. | '-PARTITIONING KEY--(----column-name-+--)--+---------------+-' column-definition |--column-name--| data-type |--+--------------------+-----------| '-| column-options |-' GDTT SYNTAX

  • Following is an explanation of some of these options:

    ON COMMIT DELETE ROWS: When a COMMIT operation is performed, all rows of the table are deleted if no WITH HOLD cursor is open on the table. This is the default.ON COMMIT PRESERVE ROWS : When a COMMIT operation is performed, all rows of the table are preserved. ON ROLLBACK DELETE ROWS : When a ROLLBACK (or ROLLBACK to SAVEPOINT) operation is performed if the table data has been changed, all rows of this table are deleted. This is default.ON ROLLBACK PRESERVE ROWS : When a ROLLBACK (or ROLLBACK to SAVEPOINT) operation is performed, all rows of the table are preserved.Note that BLOB, CLOB, DBCLOB, LONG VARCHAR, LONG VARGRAPHIC, XML, reference, and structured types cannot be used as data type for the columns of declared global temporary tablesEXPLANATION

  • To use DB2 GDTT you need to perform the following steps: Step 1. Ensure that a user temporary table space exists. If a user temporary table space does not exist, issue a CREATE USER TEMPORARY TABLESPACE statement using the followingsyntax:CREATE USER TEMPORARY TABLESPACE usr_tbsp MANAGED BY SYSTEM USING ('c:\temp\usertempspace') ; Step 2. Issue a DECLARE GLOBAL TEMPORARY TABLE statement in your application using syntax provided above. Here is an example: DECLARE GLOBAL TEMPORARY TABLE temp_proj (projno CHAR(6), projname VARCHAR(24), projsdate DATE, projedate DATE,) WITH REPLACE ON COMMIT PRESERVE ROWS NOT LOGGED IN usr_tbsp ;

    GDTT EXAMPLES

  • The schema for a declared temporary tables is always SESSION. Step 3. When you reference this table in your procedure, you need to qualify the temporary table with schema SESSION. The following example demonstrates the use of temporary tableCREATE PROCEDURE DB2ADMIN.temp_table ( )P1: BEGIN DECLARE GLOBAL TEMPORARY TABLE temp1 AS ( SELECT deptnumb as dnum, deptname as name, manager as mgr FROM org ) DEFINITION ONLY ON COMMIT PRESERVE ROWS; BEGIN DECLARE c1 CURSOR WITH RETURN FOR SELECT dnum, mgr FROM SESSION.temp1; INSERT INTO SESSION.temp1 (dnum, name, mgr) (SELECT deptnumb, deptname, manager FROM org); OPEN c1; END;

    *