Db2

6,683 views

Published on

a db2 proarmmer's guide!

Published in: Technology
4 Comments
5 Likes
Statistics
Notes
  • For IBM Mainframe Online Training , Register at http://www.todaycourses.com
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Experience Marketing Manager, ID: 23221520f6c009b2 Marketing Manager, Apple Store mba, Apple dba.bba.mba, dr.reyhanriz abbas. Education University of Illinois at Chicago Doctor of Education (EdD), Business/Managerial Economics 2016 - 2022 Columbia University in the City of New York Doctor of Education (Ed.D.), Marketing 2015 - 2019
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Thank you for sharing this wonderful guide. It is a complete guide on DB2 and very helpful for those who want to learn DB2 in short span of time. Thanks and keep posting.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • is cool
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
6,683
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
300
Comments
4
Likes
5
Embeds 0
No embeds

No notes for slide

Db2

  1. 1. DB2 UDB for z/OS Application Programming Workshop Wu Chi 027- 87544884 [email_address]
  2. 2. Application Programming Workshop Prior to attending this course, the student should already have experience with one of the supported programming languages, COBOL or PL/I for z/OS, or C language for UNIX, Windows, and OS/2. Students are also expected to already be able to construct and use SQL statements.
  3. 3. DB2 Slides -- Index Topic Slide # INTRODUCTION 4 TSO: Logging On and ISPF Initialization 21 DB2: Basics 37 DB2 Class Example 71 DB2 Concept 85 DB2 and Data Definition Language 110 DB2 and Data Control Language 142 DB2 and Data Manipulation Language (DML) 150 Batch TSO and Embedded SQL 175 DB2 and COBOL 228 EXPLAIN and Utilities in DB2 304 QMF: Query Management Facility 324
  4. 4. DB2 Family
  5. 5. DB2 Product Components
  6. 7. Introduction <ul><li>Components of a DB2 environment: </li></ul><ul><li>Users </li></ul><ul><li>Data </li></ul><ul><li>Programs(static,Dynamic) </li></ul><ul><li>System </li></ul>
  7. 8. End-User’s View They See tables & issue SQL DML statements Don’t see other programs; Don’t worry about data integrity, and so on
  8. 9. Table:---> Table name Row having the same structure Column(Field) --> Column Name The sequence of the rows is irrelevant The sequence of the columns is irrelevant
  9. 10. DML language SELECT * FORM EMP WHERE EMPNO=‘000010’ UPDATE INSERT DELETE
  10. 11. Static end users Use specific programs(transactions) to perform specific actions on DB2 data. Need not knonw SQL, DB2
  11. 12. The Static Program’s View Contain built-in or embedded SQL statements At execution time, those SQL statements will be executed by Loading the needed access paths into storage and Completing the missing variables with input from a dataset or terminal. The access path is determined at compilation time, the access logic will always be the same.
  12. 13. The Dynamic Program’s View Don’t have complete built-in SQL statements but ask for the SQL statements(or parts of SQL statements such as a WHERE clause) at Execution Time. The access path could not be determined at compilation time since a fundamental part of the statement, or the entire statement, was until execution of the program.
  13. 14. Vendor Program View Use a different interface to communicate with DB2: CLI(Call Level Interface) or ODBC. Similar to the use of dynamic SQL but reduce the need for administration . DB2 environment setup need only once. Additional advantage: portability
  14. 15. The Internet User’s View Access DB2 without being aware of this fact. Net.data provides the user with the link between the Web page and the database.
  15. 16. Program’s View- General Each program accesses tables as if it were the only one to do so. Doesn’t worry about: integrity, concurrency
  16. 17. Program’s Responsibility: LUW(Logical Unit of Work) A 2000 1000 1000 1000 B 3000 3000 4000 4000 A 2000 1000 1000 2000 B 3000 3000 4000 3000 Transfers $1000 from account A to account B LUW UPDATE A UPDATE A UPDATE B UPDATE B COMMIT ROLLBACK
  17. 18. Program’s Responsibility: Checkpoint / Restart LUW LUW LUW LUW LUW LUW LUW LUW
  18. 19. The System’s View DB2 receives many requests from many programs: Tso, Batch, CICS, IMS DB2 also receives requests form UTILITIES: SPUFI, QMF(COPY, LOAD...) work at the OBJECT level Run in BATCH Compete with the user programs for resources Understand control statements, not SQL CONCURRENTLY ACCESSING the same data
  19. 20. The System’s View DB2’S Responsibilies SECURITY CONSISTENCY CONCURRENCY PERFORMANCE METADATA
  20. 21. The DB2 Family MAINFRAME servers LAN clients
  21. 22. ROLES and Interfaces in DB2
  22. 23. Application Life Cycle
  23. 24. TSO Time Sharing Option Logging on & ISPF Initialization
  24. 25. To start a TSO session: 1. In win95, start a Winsock 3270 telnet session by clicking the start menu, general applications, communications, and then qws3270 You should have a window that looks like this:
  25. 26. Continue to hit <ENTER> at *** until you get a READY prompt. If you have any problems or errors with ISPFINIT, please notify your instructor. Once you successfully complete the ISPFINIT, at the READY prompt type: ISPF . Your screen should look like this: Press <Enter> to remove IBM license message . Note: All TSO sessions after this will begin with this ISPF screen after the initial logon.
  26. 27. Before using DB2 you must allocate a partitioned dataset . To Allocate a TSO partitioned dataset that will be used by DB2: Type ‘3’ at the Option prompt of the ISPF Primary Option Menu then <ENTER>.
  27. 28. Next: Type ‘2’ at the Option prompt of the Utility Selection Panel then <ENTER>
  28. 29. Now: Type ‘A’ at the Option prompt of the Data Set Utility panel. Use the ‘Tab’ key to move to next field to enter. When finished hit the <ENTER> key. Type your ‘USERID’ ‘ DB2’ ‘ SPUFI’
  29. 30. Type ‘HZUWK3’ ‘ TRKS’ ‘ 5’ ‘ 5’ ‘ 1’ ‘ FB’ ‘ 80’ On the Allocate New Data Set menu: Use the ‘Tab’ key to move to next field to enter. When finished hit the <ENTER> key.
  30. 31. The other ISPF option you might find useful is ‘View’. To use this option type a ‘1’ at the Option prompt of the ISPF Primary Option Menu.
  31. 32. On the View Entry Panel: Use the ‘Tab’ key to move to next field to enter. When finished hit the <ENTER> key. Type your ‘’ ‘ DB2’ ‘ SPUFI’
  32. 33. On the View screen, you will see a listing of all the members in your ‘Z#.DB2.SPUFI’ account. Use the ‘Page Up’ and ‘Page Down’ buttons to scroll pages. To see the contents of a dataset, use the ‘Tab’ key to position the cursor to the left of the name of the member, type an ‘S’, and hit <ENTER> Z999999 Z999999 Z999999 Z999999 Z999999 Z999999 Z999999 Z999999 Z999999 Z999999 Z999999 Z999999 Z999999.DB2.SPUFI
  33. 34. The screen below is the result of the ‘S’ request on the ALTTAB member. Z999999.DB2.SPUFI (ALTTAB)
  34. 35. NOW to get to DB2: Type ‘M’ at the Option prompt for the menu of Miscellaneous programs.
  35. 36. Then from the next menu choose option ‘2’ -- DB2I. Now you can start learning DB2!
  36. 37. <ul><li>Type 2 to delete the data set without printing and then press </li></ul><ul><li><ENTER>. </li></ul><ul><li>Once you see the READY prompt you are out of ISPF. </li></ul><ul><li>To logoff of the mainframe type: </li></ul><ul><li>LOGOFF and press <ENTER>. </li></ul><ul><li>To go back to ISPF type: </li></ul><ul><li>ISPF and press <ENTER> </li></ul>Logging off of TSO To end a session of TSO, press F3 until you reach the “Specify Disposition of Log Data Set” panel.
  37. 38. Type ‘2’ to delete without printing Then press <ENTER> to choose SYSOUT class A and exit ISPF
  38. 39. Then at the READY prompt, type either LOGOFF to terminate your session or type ISPF to return to ISPF main menu
  39. 40. DB2
  40. 41. <ul><li>A relational DBMS that runs on IBM mainframe computers under MVS. </li></ul><ul><li>Uses industry-standard SQL as central component. </li></ul><ul><li>Allows for interactive , and application program processing </li></ul>Interactive : Customer Information Control System (CICS) Information Management System (IMS) Time Sharing Option (TSO) and DB2I Application Programming : COBOL DB2 ( D ata b ase 2 )
  41. 42. DB2I TOPICS <ul><li>SPUFI (SQL Processor Using File Input) </li></ul><ul><li>DCLGEN </li></ul><ul><li>Program Preparation Panel </li></ul><ul><li>Running a program under DB2I </li></ul><ul><li>The following are good books on DB2: </li></ul><ul><ul><li>DB2 Developer’s Guide, Third Edition </li></ul></ul><ul><ul><ul><li>by Craig S. Mullins </li></ul></ul></ul><ul><ul><li>DB2 for the COBOL Programmer, Part I: An Introductory Course </li></ul></ul><ul><ul><li>DB2 for the COBOL Programmer, Part II: An Advanced Course </li></ul></ul><ul><ul><ul><li>both by Steve Eckols </li></ul></ul></ul>
  42. 43. <ul><li>Allows you to interactively enter SQL statements, submit them for execution, and get immediate feedback at your terminal. </li></ul>SPUFI ( S QL P rocessor U sing F ile I nput) Terminal user SPUFI DB2 Output (print) data set Tables Input data set
  43. 44. To get to SPUFI in DB2: Type ‘M’ at the Option prompt for the menu of Miscellaneous programs.
  44. 45. Then from the next menu choose option ‘2’ -- DB2I. Now type a ‘1’ at the “DB2I PRIMARY OPTION MENU
  45. 46. SPUFI’s Main Menu consists of three sections: 1. Information about the input data set 2. Information about the output data set 3. Processing Options (steps SPUFI works through) NOTE: The F1 help of SPUFI is NOT available.
  46. 47. <ul><li>Input data sets contain the SQL statements you want to execute. </li></ul><ul><li>If the data set is not cataloged or is password protected, </li></ul><ul><li>you need to supply the appropriate information for the </li></ul><ul><li>VOLUME SERIAL and DATA SET PASSWORD fields. </li></ul><ul><li>The dataset name is the one you specified when allocating the dataset in TSO and should be: </li></ul><ul><ul><li>‘ DB2.SPUFI(member name)’ </li></ul></ul><ul><li>Your USERID will be added to the front by TSO </li></ul><ul><li>Record format either F or FB </li></ul>Input data set Data set type: Sequential or partitioned Allocation: Must be already allocated Record size: 79 or 80 characters
  47. 48. <ul><li>Output data set are the resulting tables from the processing </li></ul><ul><ul><li>of the SQL statements </li></ul></ul><ul><li>If the output data set does not exist, it will be created </li></ul><ul><ul><li>dynamically by DB2. However, if the data set already exists, DB2 will overwrite the existing data set with the resulting dataset of this session. </li></ul></ul><ul><li>Name your output dataset as follows </li></ul><ul><li>RESULT </li></ul><ul><li>This dataset will be named ‘USERID.RESULT’ . </li></ul><ul><li>This dataset will be overwritten after each execution. </li></ul><ul><li>If you wish to keep a new result, name the dataset ‘RESULTn’. </li></ul>Output (print) data set Data set type: Sequential Allocation: May be allocated dynamically Record size: 80 character minimum (4092 is the default)
  48. 49. If you press <ENTER> after supplying the input and output data set information, SPUFI will then step through the enabled processing options in the order they appear in the SPUFI main menu. There are 5 processing options: Change Defaults (leave this set to ‘NO’), Edit, Execute, Auto Commit, and Browse. ** After each option is completed, an asterisk replaces the ** ** YES next to that option in the main menu. **
  49. 50. Change Defaults (leave this set to ‘NO’): The change defaults panel allows you to change any of nine options that relate to the processing of input data sets and the format of the resulting output of that processing.
  50. 51. 1. ISOLATION LEVEL 2. MAX SELECT LINES 3. RECORD LENGTH 4. BLOCK SIZE 5. RECORD FORMAT 6. DEVICE TYPE 7. MAX NUMERIC FIELD 8. MAX CHAR FIELD 9. COLUMN HEADING Used to create output data set. The nine options are:
  51. 52. ISOLATION LEVEL -- The performance and integrity, values RR (default,Repeatable Read) and CS(Cursor Stability). MAX SELECT LINES -- specifies how many rows SPUFI will include in its output data set when it processes a SELECT statement (default is 250). RECORD LENGTH, BLOCK SIZE, RECORD FORMAT, and DEVICE TYPE Unless you use SPUFI output for something other than browsing in ISPF, you shouldn’t change these values. Logical length must be at least 80. The generic DEVICE type is SYSDA, which allows MVS to decide where to put the data set. Don’t change this setting unless you need to store the output on a specific volume.
  52. 53. MAX NUMERIC FIELD -- maximum width a numeric column of a table can have. MAX CHAR FIELD -- maximum width of a character field. COLUMN HEADING -- Lets you specify how SPUFI should identify the columns in its output. NAMES names of columns as headings LABELS names columns with values specified by DBA with SQL LABELS ON statement ANY use any available label; uses names for any column without a label. BOTH use both labels and column names for headings.
  53. 54. Edit Edit is where you can create or modify input files with the ISPF editor. When you enter a “YES” at #6 of ‘Specify processing options’ , you will enter “EDIT” mode.
  54. 55. ‘ Z999999.DB2.SPUFI(SQLPGM)’ Create new Dataset: Use the Tab key to position yourself at the first column of the first empty line AND to move to the next line during typing. Now start typing your SQL statements. When you are finished, hitting return will cause the editor to place a ‘Bottom of Data’ message on the next line and quit insertion.
  55. 56. Pressing F3 during an EDIT session will accept the new input file and return to the SPUFI main menu to execute the next step. ‘ USERID.DB2.SPUFI(SQLPGM)’ PRESS ‘F3’ ‘ USERID .DB2.SPUFI(SQLPGM)’
  56. 57. Modifying an existing Dataset: Use the Tab key to position yourself at the last column of the line numbers. Insert an ‘I’ and hit return. A new line is created, insert mode is established. New lines can be entered using the <ENTER> key until an <ENTER> is pressed on a blank line at which time, insertion is stopped.
  57. 58. A ‘d’ in the last column of the line numbers can be used to delete a line. Also note: A comment is made by placing a ‘-’ in the first column of the code. Note: The arrow keys and/or mouse may be used to position the cursor anywhere within the edit screen.
  58. 59. EXECUTE After editing the dataset, pressing F3 will return you to the SPUFI main menu with an ‘*’ in option #6 of ‘Specify processing options’ . Now press <ENTER> to go to next step which is the EXECUTION of the program named. (Option #7 must be set to “yes”.) ‘ Z999999.DB2.SPUFI(SQLPGM)’ If option #9 is set to ‘YES’, you will immediately go into ’BROWSE OUTPUT’ upon completion of the execution.
  59. 60. Auto Commit Commits any changes made by the executed SQL statements automatically. (Leave ‘YES’ in option #8 of ‘Specify processing options’; we will always automatically commit.) <ul><li>Browse Output </li></ul><ul><li>Allows you to see the results of an execution. It displays </li></ul><ul><li>the statements processed, resulting tables, and status </li></ul><ul><li>information about the statements processed. </li></ul><ul><ul><li>After all of the SQL is processed, SPUFI displays status lines for the entire session. Displays whether the changes were committed, and the statistics on the number of items processed during the session, both for input and output. </li></ul></ul>
  60. 61. <ul><ul><li>A successful SQL operation is signified by a positive SQLCODE--usually a ‘0’ or a ‘100’. </li></ul></ul>Output of SQL Statements <ul><ul><li>For each SQL statement, </li></ul></ul><ul><ul><li>SPUFI shows the number of rows affected and SQLCODE it returned. </li></ul></ul>Attribute Names Data in RESULT dataset
  61. 62. An error in DB2 is signified by a negative return code. If an error occurs a screen such as the following one will occur. You should be able to fix the error by reading the message printed.
  62. 63. Browsing output in SPUFI Use the Page Up (F7)and Page Down (F8)keys to advance through the result of the SQL output by pages. Use the  Arrow keys to scroll through the result line-by-line. Use the  Arrow keys to scroll left and right through the result. To issue a find command, at the command line type ‘ FIND xxxxxxx ’ (no quotes) where ‘xxxxxxx’ is the value you wish to find. To issue another find of the same character string, hit F5 . Repeated use of F5 causes subsequent finds of the same character string. When finished Browsing, hitting the F3 key will take you back to the SPUFI main menu screen.
  63. 64. Each SQL statement must end with a semi-colon. Correct: select * from Person; Incorrect: select fac_SSN; from TEACHER; Only one SQL statement per line. Correct: Select * from Student where Student_SSN = 888888888; Select * from Course; Incorrect: Select * from Student where GPA > 3.0; Select Fac_SSN from Teacher; DB2I SQL RULES in SPUFI:
  64. 65. SQL statements allowed under SPUFI <ul><li>Simple and complex SELECT statements and groups of </li></ul><ul><li>statements </li></ul><ul><li>DML statements -- I.e. COMMIT, DELETE, INSERT, </li></ul><ul><li>ROLLBACK, SELECT, and UPDATE </li></ul><ul><li>DDL statements -- I.e. ALTER INDEX, ALTER TABLE, </li></ul><ul><li>CREATE INDEX, CREATE SYSNONYM, CREATE TABLE, </li></ul><ul><li>CREATE VIEW, DROP, and EXPLAIN </li></ul><ul><li>SQL statements not allowed under SPUFI </li></ul><ul><li>Cursor-related processing </li></ul><ul><li>Dynamic SQL </li></ul><ul><li>Pre-compiler functions </li></ul><ul><li>Features related to program variables </li></ul><ul><li>(Host and Indicator variables) </li></ul>
  65. 66. EXAMPLES of DB2 SQL run in SPUFI The following slides are examples of SQL statements that have been entered using SPUFI. The output is shown through the Browse option of SPUFI. Example 1: Shows the complete process from the SPUFI main menu through the execution and back to the main menu. Examples 2 - 3: Show only the SQL statements and the output browse screens.
  66. 67. <ul><li>Tab to the first space of the first line </li></ul><ul><li>Enter documentation (use tab key to move between lines) </li></ul><ul><li>Type the correct SQL statement (don’t forget the semicolon ‘;’ at the end. </li></ul><ul><li>When finished hit <ENTER> and F3 </li></ul>Example 1 continued
  67. 68. Example 1: Create a dataset called SHOWSTUD in your DB2 partitioned dataset using SPUFI that will list all the records in the STUDENT table . Specify all the processing options using the tab key. When finished hit <ENTER>.
  68. 69. Press <ENTER> to go to EXECUTE Example 1 continued
  69. 70. First Screen of output Hit Page Down to get to second and last screen of output . Example 1 continued When finished hit F3 to go back to SPUFI main menu.
  70. 71. Example 2:
  71. 72. This is the output from two screens combined. Example 2 continued
  72. 73. Example 3: The SQL dataset The Output dataset with the “Count” Displayed
  73. 74. DB2 Class Example
  74. 75. Relations PERSON ( SSN, FNAME, LNAME, STREET_ADDRESS, CITY, STATE, ZIP, PHONE# ) STUDENT ( SSN, CLASSIFICATION, GPA, TOTAL_HOURS ) COURSE ( COURSE#, TITLE, DESCRIPTION, COURSE_LEVEL, CREDIT_HOURS ) TEACHER ( SSN, OFFICE#, OFFICE_PHONE# ) SECTION ( SECTION#, ROOM#, MEETING_DAYS, MEETING_TIME, MAX_ENROLL, FAC_SSN, COURSE#, SEMESTER, YEAR ) TRANSCRIPT ( SSN, COURSE#, GRADE, SEMESTER, YEAR )
  75. 76. <ul><li>Relationship Requirements </li></ul><ul><li>One student may take many courses </li></ul><ul><li>A student may take many sections, but only 1 section of a given </li></ul><ul><li>course during a single semester </li></ul><ul><li>One course can be taught by many instructors and taken by </li></ul><ul><li>many students </li></ul><ul><li>One teacher may teach many different courses during one </li></ul><ul><li>semester </li></ul><ul><li>A section of a course can be taught by only 1 instructor by can be </li></ul><ul><li>taken by many students. </li></ul>
  76. 77. <ul><li>Relationship Constraints </li></ul><ul><li>A person’s SSN, FNAME, and LNAME must present to be added </li></ul><ul><li>to the database. </li></ul><ul><li>A student’s SSN must be present to be added to the database. </li></ul><ul><li>A student may take up to 20 credit hours from a maximum of 15 </li></ul><ul><li>sections per semester. </li></ul><ul><li>A course’s COURSE# , TITLE and DESCRIPTION must be </li></ul><ul><li>present to be added to the database. </li></ul><ul><li>A teacher’s FAC_SSN must be present to be added to the database. </li></ul><ul><li>One teacher may teach up to 5 sections from a maximum of 3 </li></ul><ul><li>different courses during one semester. </li></ul><ul><li>A section’s SECTION#, MAX_ENROLL, COURSE#, </li></ul><ul><li>SEMESTER, and YEAR must be present to be added to the </li></ul><ul><li>database. </li></ul><ul><li>The number of students enrolled in a section must be </li></ul><ul><li><= MAX_ENROLL. </li></ul><ul><li>A transcript’s SSN, COURSE#, GRADE, SEMESTER, and YEAR </li></ul><ul><li>must be present to be added to the database. </li></ul>
  77. 78. PERSON STUDENT TEACHER Relations in Example Database
  78. 79. COURSE SECTION
  79. 80. TRANSCRIPT
  80. 81. Query 1 Query 2
  81. 82. Query 3
  82. 83. Query 4
  83. 84. Query 5
  84. 85. Query 6
  85. 86. Query 7
  86. 87. Query 8
  87. 88. DB2 And SQL
  88. 89. DB2 Concept DB2 Data Structures <ul><li>Database </li></ul><ul><li>Storage Group </li></ul><ul><li>Table Spaces </li></ul><ul><li>Tables </li></ul><ul><li>Indexes </li></ul><ul><li>Views </li></ul>
  89. 90. DB2 Structure Storage Group: STG1 (STOGROUP) DATABASE DB1 INDEX A INDEX C Storage Group: STG2 TABLE A TABLE B Tablespace: TS1 TABLE C Tablespace: TS2
  90. 91. DB2 Structure Definitions STORAGE GROUP : STOGROUP -- A DB2 definition for a set of physical DASDs that the tablespaces are allocated onto. TABLESPACE : The physical structure (VSAM files) that contains the actual table or tables and index data. DATABASE : The logical defintion which relates a set of tablespaces to each other, and also relates particular storage groups to tablespaces and indexes. TABLE : The object which actually contains all the data. It consists of rows and columns.
  91. 92. DB2 Concept The Hierarchy of DB2 Structures Database D1 Table T1 Table T2 Table space S1 Index X1 Index X2 Table T3 Part 1 Table T3 Part 2 Partitioned Table space S2 Partitioned index X3 Part 2 Partitioned index X3 Part 2 Storage Group G1 3390 Storage Group G2 3380
  92. 93. DB2 Concept The Hierarchy of DB2 Structures Storage Group Database Table Space Table Column Index View Alias Synonym
  93. 94. DB2 Concept Database/Storage Groups Database <ul><li>contain all the data associated with one application or with </li></ul><ul><li>group of related application </li></ul><ul><li>allows you to start or stop access to all the data in one </li></ul><ul><li>operation and authorization for access to all the data as a single </li></ul><ul><li>unit </li></ul>Storage Groups <ul><li>a set of DASD volumes from which DB2 can assign space for </li></ul><ul><li>tablespaces and indexspaces </li></ul><ul><li>all volumes of a given storage group must the same device type </li></ul>
  94. 95. DB2 Concept Table Spaces Table Spaces <ul><li>is one or more data sets in which one or more tables are stored </li></ul><ul><li>can consist of from 1 to 64 VSAM data sets which can together </li></ul><ul><li>contain up to 64 gigabytes </li></ul><ul><li>are divided into equal-sized units, called pages(4k), which are </li></ul><ul><li>written to or read from DASD in one operation </li></ul><ul><li>types of Table Space </li></ul><ul><ul><li>Simple Table Spaces </li></ul></ul><ul><ul><li>Segmented Table Spaces </li></ul></ul><ul><ul><li>Partitioned Table Spaces </li></ul></ul>
  95. 96. DB2 Concept Simple Table Spaces Simple Table Spaces page page page page page page <ul><li>Not partitioned or segmented </li></ul><ul><li>can contain more than one table </li></ul><ul><li>the rows of different tables are </li></ul><ul><li>not keep separate </li></ul><ul><li>find all the rows of one table can </li></ul><ul><li>require scanning the entire table </li></ul><ul><li>space </li></ul><ul><li>if a table is dropped, its rows are </li></ul><ul><li>not deleted. </li></ul><ul><li>Space occupied by the rows does </li></ul><ul><li>not become available until the </li></ul><ul><li>table space is reorganized </li></ul>Table Space
  96. 97. DB2 Concept Segmented Table Spaces Table A Table B Table C Segmented Table Spaces <ul><li>divided into groups of pages called </li></ul><ul><li>segments, each the same size </li></ul><ul><li>intended to hold more than one table </li></ul><ul><li>each segment contains rows from </li></ul><ul><li>only one table </li></ul><ul><li>not necessary to scan the entire </li></ul><ul><li>table space but only the segments </li></ul><ul><li>that contain that table to search all the </li></ul><ul><li>rows for one table </li></ul><ul><li>if a table is dropped, its segments become </li></ul><ul><li>immediately reusable. </li></ul>Table Space page Segment 3 page Segment 2 Segment 1 page
  97. 98. DB2 Concept Partitioned Table Spaces Partitioned Table Spaces <ul><li>divided into separate units of storage </li></ul><ul><li>called partitions, each containing a part </li></ul><ul><li>of one table </li></ul><ul><li>can be independently assigned to </li></ul><ul><li>separate storage groups </li></ul><ul><li>improved data availability </li></ul><ul><li>improved utility performance </li></ul><ul><li>improved efficiency in table space and </li></ul><ul><li>index scan </li></ul>Key range A~H Key range I~Q Key range R~Z Table Space page Partition 3 page Partition 2 Partition 1 page
  98. 99. DB2 Concept Table/Index Table <ul><li>collections of rows all having the same columns </li></ul><ul><li>all the data in a given column must be of the same data type </li></ul><ul><li>can have a primary key whose values uniquely each row </li></ul>Index <ul><li>an ordered set of pointers to the data in a DB2 table </li></ul><ul><li>stored separately from the table </li></ul><ul><li>can create an index on a table any time after you create the table </li></ul><ul><li>users of the table are unaware that an index is being used. </li></ul><ul><li>DB2 decides whether or not to use the index to access the table </li></ul><ul><li>Improve performance </li></ul><ul><li>ensure uniqueness </li></ul>
  99. 100. DB2 Concept Views Views <ul><li>an alternate way of representing data that </li></ul><ul><li>exists in one or more tables </li></ul><ul><li>can include all or some of the columns </li></ul><ul><li>from one or more base tables </li></ul><ul><li>can be based on other views or on a </li></ul><ul><li>combination of views and tables </li></ul><ul><li>can be used as though it were a </li></ul><ul><li>table </li></ul><ul><li>a table has a storage representation </li></ul><ul><li>but a view does not. DB2 just stores the </li></ul><ul><li>definition of the view in the DB2 catalog </li></ul><ul><li>cannot create an index on it </li></ul>User 1 Table 1 Table 2 Table 3 Table 4 View 1 View 2 View 3 User 2
  100. 101. Physical Design Issue Designing Tables and View <ul><li>decide what data to record in database </li></ul><ul><li>define tables for each type of relationship </li></ul><ul><ul><li>one to many and many to one </li></ul></ul><ul><ul><li>many to many </li></ul></ul><ul><ul><li>one to one </li></ul></ul><ul><li>normalize your tables to avoid redundancy </li></ul><ul><li>consider denormalizing your tables for performance </li></ul><ul><li>consider creating views of your tables </li></ul><ul><ul><li>to provide a customized table for a specific user </li></ul></ul><ul><ul><li>to limit access to certain kinds of data </li></ul></ul><ul><ul><li>to allow you to alter tables without affecting </li></ul></ul><ul><ul><li>application program </li></ul></ul>DB2 Concept Physical Design Issue
  101. 102. DB2 Concept Physical Design Issue Physical Design Issue Designing Columns <ul><li>Choose a name for the column </li></ul><ul><ul><li>column name </li></ul></ul><ul><ul><ul><li>name must unique within in table </li></ul></ul></ul><ul><ul><ul><li>max length is 18 bytes </li></ul></ul></ul><ul><ul><ul><li>First character alphabetic </li></ul></ul></ul><ul><ul><li>column labels </li></ul></ul><ul><ul><ul><li>give a more descriptive column heading for a column name </li></ul></ul></ul><ul><li>What kind of data is valid for the column </li></ul><ul><ul><li>string data type </li></ul></ul><ul><ul><li>numeric data type </li></ul></ul><ul><ul><li>date, time and timestamp </li></ul></ul>
  102. 103. DB2 Concept Physical Design Issue Physical Design Issue Designing Columns DATA TYPE String Data Type CHAR(x) CHARACTER(x) VARCHAR(X) * Approximately, assuming 4K page. True maximum length depends on lengths of other columns, as well as &quot;page&quot; size. DESCRIPTION fixed length string variable length string (or longer than 254 char) LENGTH x characters (maximum 254) 0 to x characters (maximum 4K*)
  103. 104. DB2 Concept Physical Design Issue Physical Design Issue Designing Columns Double byte Data Type DATA TYPE GRAPHIC(x) VARGRAPHIC(x) * Approximately, assuming 4K page. True maximum length depends on lengths of other columns, as well as &quot;page&quot; size. DESCRIPTION fixed length string variable length string (or longer than 127 char) LENGTH x characters (maximum 128) 0 to x characters (maximum 2K*)
  104. 105. DB2 Concept Physical Design Issue Physical Design Issue Designing Columns Numeric Data Type DATA TYPE SMALLINT INTEGER INT DECIMAL(x,y) DEC(x,y) NUMERIC(x,y) FLOAT(m) REAL FLOAT FLOAT(n) DOUBLE PRECISION * Approximately **1 <= m <= 21, 22 <= n <= 53 DESCRIPTION Whole numbers Whole numbers x digits, of which y are to the right of the decimal point short floating point ** log floating point ** RANGE  32K*  2 Billion up to 32 digits 5.4E-79 to 7.2E+75 5.4E-79 to 7.2E+75
  105. 106. DB2 Concept Physical Design Issue Physical Design Issue Designing Columns Date, Time, Timestamp Data Type DATA TYPE DATE TIME TIMESTAMP INTERNAL FORMAT yyyymmdd hhmmss yyyymmddhhmmssnnnnnn (nnnnnn = microseconds)
  106. 107. DB2 Concept Physical Design Issue Physical Design Issue Designing Columns <ul><li>Which columns might need default values </li></ul><ul><ul><li>Null value </li></ul></ul><ul><ul><ul><li>not a zero, a blank, an empty string </li></ul></ul></ul><ul><ul><ul><li>any column can contain null values </li></ul></ul></ul><ul><ul><li>Default value </li></ul></ul><ul><ul><ul><li>specified with the DEFAULT clauses in CREATE TABLE </li></ul></ul></ul><ul><ul><ul><li>or ALTER TABLE </li></ul></ul></ul><ul><ul><ul><li>can be either DB2-defined or user-defined </li></ul></ul></ul><ul><ul><ul><li>DB2-defined defaults </li></ul></ul></ul><ul><ul><ul><ul><li>Number : zero String : blank </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Date : current date Time : current time </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Timestamp : current timestamp </li></ul></ul></ul></ul>
  107. 108. DB2 Concept Physical Design Issue Physical Design Issue Designing Index <ul><li>a table can have more than one index </li></ul><ul><li>index key can use one or more columns(2-64 columns) </li></ul><ul><li>column updates require index updates </li></ul><ul><li>a composite key might be useful than a key on a single column </li></ul><ul><li>when the comparison is for equality </li></ul><ul><li>indexes are important tools for improving performance </li></ul><ul><li>DB2 allow you to enter duplicate values in a key column </li></ul><ul><li>in a composite key the index entries can be in sequence by the </li></ul><ul><li>ascending values or descending values </li></ul>
  108. 109. DB2 Concept Physical Design Issue Physical Design Issue <ul><li>Primary Key : The column or set of columns that provide the </li></ul><ul><li>unique identifiers of the row </li></ul><ul><li>Foreign Key : A column or set of columns that refer to a primary </li></ul><ul><li>key </li></ul><ul><li>Parent and Dependent Table: The table containing the primary </li></ul><ul><li>key is called the parent table and the one containing the foreign </li></ul><ul><li>key is the dependent table </li></ul>Data Integrity - Terminology
  109. 110. DB2 Concept Physical Design Issue DEPTNO ... C01 DEPTNAME ....... INFORMATION CENTER PRIMARY KEY OPERATIONS ... ... ... ... ... ... E11 DEPARTMENT table FOREIGN KEY EMPNO 000030 000090 000130 000290 000300 .... FIRSTNM SALLY EILEEN DOLORES JOHN PHILIP .... LASTNAM KWAN HENDERSON QUINTANA PARKER SMITH .... ... ... ... ... ... ... ... DEPT C01 E11 C01 E11 E11 ... ... ... ... ... ... ... ... PRIMARY KEY EMPLOYEE table
  110. 111. DB2 Concept -- Referential Integrity <ul><li>By definition, a FOREIGN KEY in one table matches </li></ul><ul><li>a PRIMARY KEY in another table </li></ul><ul><li>A PRIMARY KEY value must be UNIQUE, and cannot be NULL </li></ul><ul><li>A FOREIGN KEY value must match a PRIMARY KEY or be NULL </li></ul><ul><li>DB2 enforcement of referential constraints: </li></ul><ul><ul><li>INSERT/UPDATE/LOAD of FOREIGN KEY </li></ul></ul><ul><li>- Must match PRIMARY KEY or be NULL </li></ul><ul><ul><li>UPDATE of PRIMARY KEY </li></ul></ul><ul><li>- Not allowed if any FOREIGN KEYS match original value </li></ul><ul><ul><li>DELETE of PRIMARY KEY </li></ul></ul><ul><li>- Rules specified by owner of table </li></ul><ul><li>CASCADE </li></ul><ul><li>SET NULL </li></ul><ul><li>RESTRICT </li></ul>Referential Integrity
  111. 112. DB2 Concept -- Referential Integrity When removing a primary key (DELETE) what should be done to matching foreign keys? 1. DELETE rows with matching values (CASCADE) 2. Change matching values to null (SET NULL) 3. Disallow the DELETE if matching values exist (RESTRICT) Referential Integrity
  112. 113. DB2 and Structured Query Language
  113. 114. SQL Summary SQL Data Definition Language (DDL) Data Manipulation Language (DML) Data Control Language (DCL) CREATE DROP ALTER SELECT INSERT UPDATE DELETE GRANT REVOKE
  114. 115. DB2 Programming Concept SQL 语言特性 : . 取代传统的 DO PROCEDURE LANGUAGE . 程序设计者 只需 申明 需要 哪些资料 ,不需 申明 如何取得 这些资料 . 不仅是数据查询 工具 ,也能进行数据管理 . 命令语法易学易懂 - SELECT * FROM DA. TBDAMF WHERE APPLID = 'DA'; - UPDATE DA.TBDAMF SET FILE = 'AAAAAA' WHERE EMPNO = '111111';
  115. 116. DB2 and Data Definition Language
  116. 117. Data Definition Language (DDL) ALTER statement : ALTER STOGROUP ALTER TABLESPACE, ALTER TABLE, ALTER INDEX CREATE statement : CREATE STOGROUP CREATE DATABASE CREATE TABLESPACE CREATE TABLE CREATE INDEX CREATE VIEW CREATE SYNONYM DROP statement : DROP STOGROUP DROP DATABASE DROP TABLESPACE DROP TABLE DROP INDEX DROP VIEW DROP SYNONYM
  117. 118. Data Definition Language (DDL) -- CREATE CREATE STOGROUP stogroup-name VOLUMES volume-id VCAT catalog-name PASSWORD password ; CREATE STOGROUP IBMST001 VOLUMES ACA301 VCAT DSNCAT PASSWORD OSESME ; Creates a storage group at the current server. Storage from the identified volumes can later be allocated for table spaces and index spaces. CREATE STOGROUP Privilege Needed: CREATESG or SYSADM or SYSCTRL
  118. 119. Data Definition Language (DDL) -- CREATE CREATE DATABASE database-name STOGROUP stogroup-name CCSID [ ASCII | EBCDIC ]; CREATE DATABASE IBMDB001 STOGROUP IBMSG001 CCSID EBCDIC ; Defines a DB2 database at the current server. CCSID: Specifies the default encoding scheme for data stored in the database. The default applies to the table spaces created in the database. All tables stored within a table space must use the same encoding scheme. CREATE DATABASE Privilege Needed: CREATDBA or CREATDBC or SYSADM or SYSCTRL
  119. 120. Data Definition Language (DDL) -- CREATE CREATE TABLESPACE tablespace-name IN database-name USING STOGROUP stogroup-name ; CREATE TABLESPACE IBMTS001 IN IBMDB001 USING STOGROUP IBMSG001 ; Defines a simple, segmented or partitioned table space at the current server. CREATE TABLESPACE Other parameters: SEGSIZE, BUFFERPOOL, LOCKSIZE, LOCKMAX, COMPRESS, CCSID, LOCPART, MAXROWS Privilege Needed: CREATETS or DBADM or DBCTRL or DBMAINT or SYSADM or SYSCTRL
  120. 121. Data Definition Language (DDL) -- CREATE CREATE TABLE table-name ( column-definition , unique-constraint , referential-constraint ) LIKE table-name IN database-name.tablespace-name ; Defines a table at the current server. The definition must include its name and the names and attributes of its columns. The other parameters are optional. CREATE TABLE Privilege Needed: CREATETAB or DBADM or DBCTRL or DBMAINT or SYSADM or SYSCTRL Note: There are more optional parameters that are used for fine tuning a table and that will not be covered here. See the DB2 manual for an explanation of these.
  121. 122. Data Definition Language (DDL) -- CREATE TABLE Column-definition: column-name data-type NOT NULL [ UNIQUE | PRIMARY KEY ] WITH DEFAULT [ constant | NULL ] references-clause Column-name : Names a column of the table. Do not use the same name for more than one column of the table. A table can have use to 750 columns.
  122. 123. Data Definition Language (DDL) -- CREATE TABLE Data-type : Specifies one of the following types: SMALLINT 2 bytes PIC S9(4) COMP INTEGER 4 bytes PIC S9(9) COMP REAL 4 bytes PIC USAGE COMP -1 FLOAT(1..21) 4 bytes PIC USAGE COMP -1 DOUBLE PRECISION 8 bytes PIC USAGE COMP -2 FLOAT(22..53) 8 bytes PIC USAGE COMP -2 DECIMAL (m,n) (m/2)+1 bytes PIC S9(m-n)V9(n) COMP -3 continued on next slide
  123. 124. Data-type : continued CHARACTER(n) n bytes PIC X(n) VARCHAR(n) 2 to n+2 01 VARCHAR. bytes 49 LENGTH PIC S9(4) COMP. 49 COLUMN PIC X(n). GRAPHIC(n) 2n bytes PIC G(n) DISPLAY -1 VARGRAPHIC(n) 2 to 2n+2 01 VGRAPHIC. bytes 49 LENGTH PIC S9(4). 49 COLUMN PIC G(n) DISPLAY -1. DATE 4 bytes PIC X(10) YYYYMMDD TIME 3 bytes PIC X(8) TIMESTAMP 10 bytes PIC X(10) Data Definition Language (DDL) -- CREATE TABLE
  124. 125. Data Definition Language (DDL) -- CREATE TABLE NOT NULL -- prevents a column from containing null values. CREATE TABLE TAB001 (PROJECT-NO CHAR(6) NOT NULL, …. ); PRIMARY KEY -- provides a shorthand method of defining a primary key composed of a single column. If coded in the definition of a column it is equivalent to coding the PRIMARY KEY as a separate clause. UNIQUE -- provides a shorthand method of defining a unique key composed of a single column. If coded in the definition of a column it is equivalent to coding the UNIQUE as a separate clause. CREATE TABLE TAB002 (PROJECT-NO CHAR(6) NOT NULL PRIMARY KEY, ….);
  125. 126. WITH DEFAULT [ constant | NULL] -- assigns a value to the column in the absence of a value specified on INSERT or LOAD. If a value is not specified after DEFAULT, the default value depends on the data type of the column. CREATE TABLE TAB001 ( …. PROJECT-NAME CHAR(20) WITH DEFAULT NULL, …. ); Data Definition Language (DDL) -- CREATE TABLE
  126. 127. References clause -- REFERENCES table-name (column-name) ON DELETE [ SET NULL | RESTRICT | CASCADE ] -- provides a shorthand method of defining a foreign key composed of a single column . If coded in the definition of a column, the effect is the same as it that references-clause were specified as part of a FOREIGN KEY clause. -- ON DELETE -- the delete rule of the relationship as follows: SET NULL -- set the foreign key attributes to NULL RESTRICT -- if there are tuples in the referenced table, cause an error to occur CASCADE -- if there are tuples in the referenced table, delete the tuples with the matching foreign key value CREATE TABLE TAB001 (…. ACCT-DEPT CHAR(3) REFERENCES TAB002 (ACCT-DEPT) ON DELETE SET NULL, ….); Data Definition Language (DDL) -- CREATE TABLE
  127. 128. Data Definition Language (DDL) -- CREATE TABLE unique-constraint -- PRIMARY KEY( column-name ,...) -- defines a primary key composed of the identified columns. The columns named MUST be defined as NOT NULL. -- UNIQUE( column-name ,…) -- defines a unique key composed of the identified columns. Each column named MUST be defined as NOT NULL. A UNIQUE key definition is a duplicate it it is the same as the PRIMARY KEY. *** NOTE : With either unique-constraint definition, in most circumstances the table is marked as unavailable until its primary key index is explicitly created. *** CREATE TABLE TAB001 (PROJECT-NO CHAR(6) NOT NULL, …. …., PRIMARY KEY (PROJECT-NO) ) IN IBMDB001.IBMTS001;
  128. 129. Data Definition Language (DDL) -- CREATE TABLE referential-constraint -- FOREIGN KEY constraint-name (column-name,...) REFERENCES table-name (column-name,….) ON DELETE …. -- defines a referential constraint with the specified name. A name is generated if constraint-name is not specified. CREATE TABLE TAB001 (PROJECT-NO CHAR(6) NOT NULL, ACCT-DEPT CHAR(3), ACCT-LOC CHAR(2), …. …., PRIMARY KEY (PROJECT-NO) FOREIGN KEY IBMFK001 (ACCT-DEPT, ACCT-LOC) REFERENCES TAB002 (DEPT, LOC) ON DELETE SET NULL ) ….
  129. 130. Data Definition Language (DDL) -- CREATE TABLE LIKE table-name or view-name -- specifies that the columns of the table have exactly the same name and description as the columns of the identified table or view. The name specified after the LIKE must identify a table or view that exists at the current server and MUST have at least a SELECT privilege set (权限) . CREATE TABLE TAB003 LIKE TAB001; IN database-name.tablespace-name or IN DATABASE database-name -- names the database and tablespace in which the table is created. Both forms are optional. Default is IN DATABASE DSNDB04 . CREATE TABLE TAB001 ……. IN IBMDB001.IBMTS001; DVLPDB.DVLPTS
  130. 131. Data Definition Language (DDL) -- CREATE CREATE INDEX Creates a partitioned or nonpartitioned index and an index space at the current server. The columns included in the key of the index are columns of a table at the current server. Privilege Needed: INDEX or DBADM or SYSADM or SYSCTRL CREATE [ TYPE n ] [ UNIQUE ] INDEX index-name ON table-name ( column-name [ ASC | DESC ] , …. ) USING STOGROUP storage-group-name CLUSTER; Note: There are more optional parameters that are used for fine tuning a table and that will not be covered here. See the DB2 manual for an explanation of these.
  131. 132. Data Definition Language (DDL) -- CREATE INDEX TYPE n -- specifies the type of index, 1 or 2 UNIQUE -- prevents the table from containing two or more rows with the same value of the index key. A table requires a unique index if a table has a UNIQUE or PRIMARY KEY clause in the CREATE TABLE statement. If the table already contains rows with duplicate key values, the index is not created. INDEX index-name -- names the index. The name, including the implicit or explicit qualifier, must not identify an index that is described in the catalog. The qualifier must not be SYSIBM, SYSCAT,SYSFUN, or SYSSTAT. ON table-name -- identifies the table on which the index is created. The name must identify a table in the current server. The table must be a base table (not a view)
  132. 133. column-name [ ASC | DESC ] -- specifies the columns of the index key. Each column-name must identify a column of the table. 16 columns or less may be specified. ASC is ascending( 升 ) order and is the default . DESC means put the index entries in descending order. USING STOGROUP -- identifies a storage group that exists at the current server and the privilege set must include SYSADM, SYSCTRL, or USE stogroup for this storage group. CLUSTER -- specifies that the index is the cluster index of the table. The cluster factor of a clustering index is maintained or improved dynamically as data is inserted into the associated table, by attempting to insert new rows physically close to the rows for which the key values of this index are in the same range. Only one clustering index may exist for a table so Do not use CLUSTER if CLUSTER was used in the definition of an existing index on the table.
  133. 134. Data Definition Language (DDL) -- CREATE INDEX If the named table already contains data, CREATE INDEX creates the index entries for it. If the table does not yet contain data, CREATE INDEX creates a description of the index; the index entries are created when data is inserted into the table. Creating an index with a schema name that does not already exist will result in the implicit creation of that schema provided the authorization ID of the statement has IMPLICIT_SCHEMA authority. The schema owner is SYSIBM. The CREATEIN privilege on the schema is granted to PUBLIC. CREATE UNIQUE INDEX IBMDB001.IBMNX001 ON IBMDB001.TAB001 ( PROJECT-NO ASC) USING STOGROUP IBMSG001 CLUSTER;
  134. 135. Data Definition Language (DDL) -- CREATE CREATE VIEW Creates a view on tables or views at the current server. Privileges are needed for each table or view referenced in the subselect. CREATE VIEW view-name ( column-name , …. ) AS subselect WITH [ CASCADED | LOCAL ] CHECK OPTION; Privilege Needed: SELECT (on each table or view) or Ownership of the table or DBADM or SYSADM or SYSCTRL
  135. 136. view-name -- names the view. The name, including the implicit or explicit qualifier, must not identify a table, view, nickname or alias described in the catalog.The qualifier must not be SYSIBM, SYSCAT, SYSFUN, or SYSSTAT column-name -- names the columns in the view. If you specify a list of column names, it must consist of as many names as there are columns in the result table of the subselect. AS subselect -- defines the view. At any time the view consists of the rows that would result if the subselect were executed. CREATE VIEW IBMDB001.IBMVW001 (PROJNO, PROJNAME, PROJDEP, EMP-NAME) AS SELECT PROJNO, PROJNAME, PROJDEP,EMP-NAME FROM PROJECT, EMPLOYEE WHERE EMP-NO = ‘12349’; Page:2-35 Data Definition Language (DDL) -- CREATE VIEW
  136. 137. The Disappearing Row 1.Create View EMPV AS Select * from EMP Where Salary > 0; 2.Insert Into EMPV Values(‘000260’,...,-6000,...); 3.Select * From EMPV Where EMPNO = ‘000260”; The inserted row disappeared! Data Definition Language (DDL) -- CREATE VIEW
  137. 138. WITH …. CHECK OPTION -- specifies the constraint that every row that is inserted or updated through the view must conform to the definition of the view. DB2 enforces this constraint whenever rows of the view are inserted or updated . If the search condition is not true for an inserted or updated row, an error occurs and no rows are inserted or deleted. CASCADED -- Update and insert operations on view V must satisfy search conditions of view V and all underlying views, regardless of whether the underlying view were defined with a check option. LOCAL -- This form lets you update or insert rows that do not conform to the search condition of view V. This operation can be performed if the view is defined on a view that was defined without a check operation. Data Definition Language (DDL) -- CREATE VIEW
  138. 139. Default Value is cascade when using V5, prior to V5 will use the local syntax. The check option can only be specified on a view that is not read-only and that does not include a subquery else the SQLCODE will be -160. 1.Create View EMPV AS Select * from EMP Where Salary > 0 With Check Option ; 2.Insert Into EMPV Values(‘000260’,...,-6000,...); error occurs and no rows are inserted Data Definition Language (DDL) -- CREATE VIEW
  139. 140. Read-Only View: -Involves a join -Contains a column function -Includes a GROUP BY clause -Contains the DISTINCT keyword -Contains a column derived from an expression or a scalar function Insertable View: --A view is insertable if ALL columns of the view are updatable and the fullselect of the view does not include UNION ALL. A view definition cannot contain UNION or ORDER BY clause (DDL) -- CREATE VIEW ( View Restrictions)
  140. 141. SYSIBM.SYSTABLES SYSIBM.SYSCOLUMNS SYSIBM.SYSVIEWS SYSIBM.SYSVIEWDP Since views are virtual tables, Db2 will keep information about them as if they were tables. In addition, the view’s definition will be stored as well as dependency information. All tables in the db2 catalog have the owner SYSIBM (DDL) -- CREATE VIEW ( View Catalog Information)
  141. 142. <ul><li>Good reasons to use views </li></ul><ul><ul><li>Views for simplicity </li></ul></ul><ul><ul><ul><li>-Elimination of unwanted data </li></ul></ul></ul><ul><ul><ul><li>-Elimination of redundant coding </li></ul></ul></ul><ul><ul><li>Views for security on data content </li></ul></ul><ul><ul><li>Views for (Program)data independence(partial) </li></ul></ul><ul><ul><li>Views to customize column names </li></ul></ul><ul><ul><li>Views to validate data for specific users (CHECK OPTION) </li></ul></ul>(DDL) -- CREATE VIEW ( Good Reasons to use views)
  142. 143. Data Definition Language (DDL) -- DROP DROP -- deletes an object at the current server. Except for storage groups, any objects that are dependent on that object are also deleted. Whenever an object is deleted, its description is deleted from the catalog at the current server. Privileges Needed: To drop a table, tablespace or index: Ownership or DBADM To drop an alias, storage group, or view: Ownership or SYSADM or SYSCTRL To drop a database: DROP privilege or DBADM or DBCTRL or SYSADM or SYSCTRL To drop a synonym: Ownership
  143. 144. Data Definition Language (DDL) -- DROP DROP DATABASE database-name ; DROP INDEX index-name ; DROP STOGROUP storage-group-name ; DROP TABLE table-name ; DROP TABLESPACE tablespace-name ; DROP VIEW view-name ; DROP SYNONYM synonym ;
  144. 145. DB2 and Data Control Language
  145. 146. Data Control Language (DCL) GRANT Statement : Grants authorization of functions and levels. GRANT privilege TO [ authorization-name | PUBLIC ] WITH GRANT OPTION; System-Wide Functions : SYSADM : A user has TOTAL CONTROL over any DB2 resource and may grant and/or revoke from any other user the authority to access any resource (expect for the actual creator of any object). GRANT SYSADM TO T90XXX1; SYSOPR : A user has the ability to issue certain DB2 commands and has no access to DB2 tables.
  146. 147. Other system-wide authorities : BINDADD : Allows user to create new application plans using the BIND subcommand with the ADD option. CREATEDBA : Allows user to create new databases and automatically gives DBADM authority over those databases. GRANT CREATEDBA TO T90XXX1, T90YYY1, … ; CREATEDBC : Allows user to create new databases and automatically gives DBCTRL authority over those database. CREATESG : Allows user to create new storage groups. STOSPACE : Allows user to use the STOSPACE utility. TRACE : Allows user to start and stop DB2 traces using the -START TRACE and -STOP TRACE Data Control Language (DCL)-- GRANT
  147. 148. Database Wide Functions : DBADM : A user has total control over those databases granted at this level of authority. This includes altering and creation of tables, creation of tablespaces, seeing and modifying data in all tables, and running appropriate utilities. The user can grant lower levels of authority to the objects in his defined database IF the user has been given GRANT option. DBCTRL : Allows a user to run utilities and to create tables and tablespaces. The user cannot access data in the tables that have been created by another user in the same tablespace without being granted specific access by the creator of the table or a SYSADM priviledge. GRANT DBADM ON DATABASE IBMDB001 TO PUBLIC ; Data Control Language (DCL)-- GRANT
  148. 149. Other database-level authorities : CREATETAB : Allows user to create tables in any existing tablespace in this database. CREATETS : Allows user to create tablespaces in this database. DISPLAYDB : Allows user to check the database and tablespace in this database through execution of the -DISPLAY DATABASE command. DROP : Allows user to drop the database. IMAGECOPY : Allows user to run the COPY and MERGECOPY utilities against tablespaces in this database. LOAD : Allows user to run the LOAD utility to load tables in the database. GRANT CREATETS ON DATABASE IBMDB001 TO T90XXX, T90YYY, T90ZZZ, …. ; Data Control Language (DCL)-- GRANT
  149. 150. Other database-level authorities : RECOVERDB : Allows user to run the RECOVER and MODIFY utilities against tablespaces in this database. REORG : Allows user to run the REORG utility against tablespaces and indexes in this database. REPAIR : Allows user to run the REPAIR utility against tablespaces and indexes in this database. STARTDB : Allows the user to start this database by issuing the -START DATABASE command. STATS : Allows user to run the RUNSTATS and CHECK utility against tablespaces and indexes in this database. STOPDB : Allows the user to stop this database by issuing the -STOP DATABASE command. Data Control Language (DCL)-- GRANT
  150. 151. Table-level Authorities : SELECT : Allows view-only access to data within a table or that data defined by a view. UPDATE : Allows user update capability to data within a table or data defined by a view. DELETE : Allows user delete capability for rows within a table. INSERT : Allows user to insert new rows in a table. ALTER : Allows user to be able to alter a table or view by adding a column. UPDATE USING COLUMN-NAME(s) : Allows user to update ONLY those columns that have been specified in the GRANT statement. ALL : Allows the user to have all the above privileges. GRANT SELECT ON TAB001 TO PUBLIC; GRANT ALL ON TAB001 TO T90XXX, T90YYY; Data Control Language (DCL)-- GRANT
  151. 152. REVOKE Statement : Revokes privileges from authorization. REVOKE privilege ON DATABASE FROM [ authorization-name | PUBLIC ] [ BY authorization-name | ALL ]; privilege : Names one or more privileges. authorization-name : Lists one or more authorization Ids. REVOKE DBADM ON DATABASE FROM PUBLIC; REVOKE CREATETS ON DATABASE FROM T90XXX1; REVOKE USE OF STOGROUP IBMSG001 FROM PUBLIC; REVOKE USE OF TABLESPACE IBMTS001 FROM T90XXX1; Data Control Language (DCL)
  152. 153. DB2 And DML
  153. 154. INSERT statement Inserts rows into a table or view. Inserting a row into a view also inserts the row into the table on which the view is based. Two forms: INSERT via VALUES is used to insert a single row into the table or view using the values provided or referenced. INSERT via SELECT is used to insert one or more rows into the table or view using values from other tables and/or views. Privilege Needed: On a table: INSERT on table or Ownership or DBADM or SYSADM ; On a view: INSERT on view or SYSADM Data Manipulation Language (DML)
  154. 155. INSERT INTO [ table-name | view-name ] VALUES (.., .., .., .., ..); INSERT INTO [ table-name | view-name ] ( column-name , …, …, ) VALUES (.., .., .., .., ..); INSERT INTO [ table-name | view-name ] subselec t ; INSERT INTO [ table-name | view-name ] ( column-name , …, …, ) subselect ; Data Manipulation Language (DML) -- INSERT
  155. 156. INSERT INTO TAB001 VALUES ( ‘00024’ , ‘Mary’ , ‘D11’ , 15 ); INSERT INTO TAB002 ( CUSTOMER-ID, CUSTOMER-NAME, CUSTOMER-ROOM-NUMBER, CUSTOMER-AGE ) VALUES ( ‘00024’, ‘Mary’, ‘D11’, 15 ); INSERT INTO VIEW001 SELECT * FROM TAB003 ; INSERT INTO VIEW002 SELECT * FROM TAB003 WHERE GPA > 3.0; Data Manipulation Language (DML) -- INSERT
  156. 157. INSERT Rules: Default values: If a value is not included in the value list, the default value is used. Columns that do not have a default value MUST have a value in the value list. Uniqueness Constraint: If the identified table or base table of a view has one or more unique indexes, each row inserted into the table must conform to the constraints imposed by those indexes. Referential Constraint: Each non-null value of a foreign key must be equal to some value of the parent key of the parent table in the relationship. Omitting the column list: If column list is omitted, a value for every column that is present in the table must be presented. Data Manipulation Language (DML) -- INSERT
  157. 158. UPDATE statement Updates the values of specified columns in rows of a table or view. Updating a row of a view updates a row of the table on which the view is based. Two forms: The searched UPDATE form is used to update one or more rows, optionally determined by a search condition. The positioned UPDATE form is used to update exactly one row, as determined by the current position of a cursor. Privilege Needed: User-defined table: UPDATE privilege or Ownership or DBADM or SYSADM View: UPDATE on view or SYSADM Data Manipulation Language (DML)
  158. 159. Searched update: UPDATE [ table-name | view-name ] SET column-name = [ expressio n | NULL ] , column-name = [ expression | NULL ], .., .., WHERE search-condition ; Positioned update: UPDATE [ table-name | view-name ] SET column-name = [ expression | NULL ] , column-name = [ expression | NULL ], .., .., WHERE CURRENT OF cursor-name ; Data Manipulation Language (DML) -- UPDATE
  159. 160. UPDATE TAB001 SET PHONE-NUMBER = ‘815-753-6945’ WHERE EMPLOYEE_NUMBER = ‘E293’ ; UPDATE TAB001 SET SALARY = SALARY + 100 WHERE EMPLOYEE_NUMBER = ‘E948’ ; Embedded in COBOL: EXEC SQL UPDATE TAB003 SET SALARY = 2 * SALARY WHERE CURRENT OF CURSOR1 ; END-EXEC. Data Manipulation Language (DML) -- UPDATE
  160. 161. UPDATE rules: If the update value is then the column MUST NULL allow NULL values number be a numeric column character string be a character string with appropriate length graphic string be a graphic string with appropriate length datetime value be a DATE, TIME or TIMESTAMP column Data Manipulation Language (DML) -- UPDATE
  161. 162. UPDATE rules continued: Uniqueness constraint: The updated row must conform to any constraints imposed on the table by any unique index on an updated column. Referential constraint: A non-null update value of a foreign key must be equal to some value of the parent key of the parent table of the relationship. Data Manipulation Language (DML) -- UPDATE
  162. 163. DELETE statement : Deletes rows from a table or view. Deleting a row from a view deletes the row from the table on which the view is based. Two forms: The searched DELETE form is used to delete one or more rows, optionally determined by a search condition. The positioned DELETE form is used to delete exactly one row, as determined by the current position of a cursor. Privilege Needed: User-defined table: DELETE privilege or Ownership or DBADM or SYSADM On a view: DELETE privilege or SYSADM Data Manipulation Language (DML)
  163. 164. Searched delete: DELETE FROM [ table-name | view-name ] WHERE search-condition ; Positioned delete: DELETE FROM [ table-name | view-name ] WHERE CURRENT OF cursor-name ; Data Manipulation Language (DML) -- DELETE
  164. 165. DELETE FROM TAB001 WHERE DEPT-NUMBER = ‘E11’ OR DEPT-NUMBER = ‘D21’ ; Embedded in COBOL program: EXEC SQL DELETE FROM TAB003 WHERE CURRENT OF CURSOR1 ; END-EXEC. Data Manipulation Language (DML) -- DELETE
  165. 166. SQL Statement Performance-access path Access Paths Typical access paths: Table(space) scan Matching index scan No-matching index scan Index-only access The Access Path is determined by the Optimizer in DB2. It can be influenced by the way you write your SQL statement.
  166. 167. Access Paths DB2 -- SQL Statement Performance Examples: Phonebook has an index on LASTNAME, FIRSTNME Table(space) Scan : SELECT * FROM PHONEBOOK SELECT * FROM PHONEBOOK WHERE ADDRESS LIKE ‘%AVE%’ Matching Index Scan : SELECT LASTNAME, FIRSTNME, PHONENO FROM PHONEBOOK WHERE LASTNAME LIKE ‘S%’
  167. 168. Access Paths DB2 -- SQL Statement Performance Index-Only Matching Index Scan : SELECT FIRSTNME FROM PHONEBOOK WHERE FIRSTNME LIKE ‘S%’ No-Matching Index Scan : SELECT LASTNAME, FIRSTNME, PHONENO FROM PHONEBOOK WHERE FIRSTNME = ‘ABE’
  168. 169. Access Paths Howell,Thurston(1) Peters,Joan(2) Zidler,Bob(3) Adams,Mark(2,1)(5,2) Alviani,Cart(7,2) Bennett,Barb(2,3) Champman,Mike(5,1) Davis,Mac(3,1) Howell,Thurston(3,2) Jefferson,Tom(4,1) Jones,Bob(1,1) Lee,Spike(4,2) Lincoln, Abe (7,1) Mitchell,David(2,3) Peters,Joan(1,3) Quinn,tony(6,2) Reeves,Susan(1,2) S mith,Stanley(8,2) S mith,Steve(8,1) Thompson,Tom(6,3) Zidler,Bob(6,1) Jones,Bob Reeves,Susan Peters,Joan Adams,Mark Mitchell,David Bennett,Barb Davis,Mac Howell,Thurston . Jefferson,Tom Lee,Spike . Champman,Mike Adams,Mark . Zidler,Bob Quinn,Tonny Thompson,Tom Lincoln, Abe Alvani,Cart . S mith,Steve S mith,Stanley . Data Pages Root Page Leaf Pages
  169. 170. SQL Statement Performance 1. Avoid Numeric Conversions SELECT A INTO :B - Column A and host-variable B should be same data type and scale ...WHERE A = :B 2. SELECT Only the columns you will use Additional columns = additional CPU 3. Avoid SELECT * - External changes to the table can cause errors or warnings DB2 -- SQL Statement Performance
  170. 171. 4. If Possible, Use Join Logic instead of Correlated Subselect SELECT EMPNO, LASTNAME FROM TEMPL, TPROJ WHERE WORKDEPT = DEPTNO AND EMPNO = RESPEMP is more efficient than SELECT EMPNO, LASTNAME FROM TEMPL WHERE WORKDEPT = (SELECT DEPTNO FROM TPROJ WHERE RESPEMP = X.EMPNO) DB2 -- SQL Statement Performance
  171. 172. 5. MINIMIZE DB2 SORT PROCESSING Don't request sequencing unless necessary - Additional CPU - Additional I/O to temporary database Consider Using an External Sort instead of ORDER BY - For a large number of rows - Will require more Virtual Storage in user Address Space - Reduces contention 争夺 for DB2 temporary database Allow DB2 to consider INDEX to avoid sort DB2 -- SQL Statement Performance
  172. 173. 6. Using an INDEX can: . Save a tablespace scan . Avoid a sort 7. Whether an existing index is usable for this access to the data - Dependent on statement coding DB2 -- SQL Statement Performance
  173. 174. INDEXED Column is... DB2's USE OF INDEXES Used with: IN LIKE BETWEEN >,>=,<,<=,  >,  <,=  =,<> NOT OR ORDER BY GROUP BY DISTINCT^ Compared to: longer literal arithmetic exp. diff. data type Used for JOIN INDEX Candidate YES NOTE1 YES YES NO NOTE2 NOTE3 YES YES YES NO NO NO YES Sort Candidate YES YES YES YES NOTE1 : YES, except when string is host-variable, or string is of the form '%...' or '-...' NOTE2 : Apply NOT, then evaluate NOTE3 : NO unless convertible to in DB2 -- SQL Statement Performance
  174. 175. SELECT...WHERE C1 = :HV+100 . CANNOT use index ------------ HV = HV+100... SELECT...WHERE C1 = :HV . CAN use INDEX SELECT...FROM TEMPL,TDEPT WHERE WORKDEPT = DEPTNO AND WORKDEPT = 'E11' . Can use index on WORKDEPT for initial selection ------------ SELECT...FROM TEMPL,TDEPT WHERE WORKDEPT = DEPTNO AND WORKDEPT = 'E11' AND DEPTNO = 'E11' . Allows DB2 to use index on WORKDEPT or DEPTNO for initial selection DB2 -- SQL Statement Performance
  175. 176. DB2 -- SQL Statement Performance SELECT ... FROM TEMPL WHERE WORKDEPT = 'A12' OR WORKDEPT = 'B12' . Can use index (DB2 can convert to IN) WHERE WORKDEPT IN('A12' , 'B12‘) SELECT ... FROM TEMPL WHERE WORKDEPT = 'A12' OR WORKDEPT > 'B12' . CANNOT use index ------------ SELECT ... FROM TEMPL WHERE WORKDEPT = 'A12’ UNION ALL SELECT ... FROM TEMPL WHERE WORKDEPT > 'B12' . CAN use index
  176. 177. USE BETWEEN IF POSSIBLE SELECT ... FROM TEMPL WHERE WORKDEPT >= 'A00' AND WORKDEPT <= 'C99' . Can use index, but... ---------------- SELECT ... FROM TEMPL WHERE WORKDEPT BETWEEN 'A00' AND 'C99' Makes more efficient use of the index DB2 -- SQL Statement Performance TO EXPLAIN
  177. 178. BATCH TSO and DB2 EMBEDDED SQL
  178. 179. DB2 Programming Concept SAMPLE PROGRAM REVIEW SAMPLE PROGRAM REVIEW <ul><li>BATCH PROGRAM </li></ul><ul><li>ON-LINE PROGRAM </li></ul>
  179. 180. <ul><li>SQL statements can be executed in DB2: </li></ul><ul><ul><ul><li>in the background </li></ul></ul></ul><ul><ul><ul><li>under control of TSO terminal monitor program </li></ul></ul></ul><ul><li>JCL to run a program in batch: </li></ul><ul><li>// jobname,…… //JOBLIB DD DSN= db2 load library name //BATCHTSO EXEC PGM=IKJEFT01,DYNAMNBR=20 //SYSTSPRT DD SYSOUT=* //SYSPRINT DD SYSOUT=* //SYSUDUMP DD SYSOUT=* //SYSTSIN DD * DSN SYSTEM( db2 program name ) RUN ( name of program to run ) - PLAN( name of the plan to use ) - LIB(‘ application library’ ) /* // </li></ul>Batch TSO
  180. 181. //T90xxxnn JOB ,'Your Name',MSGCLASS=A,REGION=0K /*JOBPARM ROOM=##,TIME=3,LINES=5,Q=F //JOBLIB DD DSN=SYS2.HLA.V120.LOADLIB,DISP=SHR // DD DSN=SYS3.DB2.V510.SDSNLOAD,DISP=SHR //DROPTABS EXEC PGM=IKJEFT01,DYNAMNBR=20 //SYSTSPRT DD SYSOUT=* //SYSPRINT DD SYSOUT=* //SYSUDUMP DD SYSOUT=* //SYSTSIN DD * DSN SYSTEM(DSN1) RUN PROGRAM(DSNTIAD) PLAN(DSNTIA51) PARM('RC0')- LIBRARY('SYS3.DB2.V510.RUNLIB.LOAD') END /* //SYSIN DD * DROP TABLE PERSON; DROP TABLE STUDENT; DROP TABLE COURSE; DROP TABLE SECTION; DROP TABLE TEACHER; DROP TABLE TRANSCRIPT; DROP DATABASE IBMDB001; /* // Batch TSO JCL to execute SQL statements IN STREAM
  181. 182. Source Program Precompiler DCLGEN DBRM Modified Source Compiler Compiled Source Linkage Editor Load Module Bind Package Package Bind Plan Plan DB2 Catalog DB2 Directory DB2 Embedded SQL -- Program Preparation
  182. 183. DB2 PROGRAM PREPARATION <ul><li>Complilers Do Not Understand SQL </li></ul><ul><li>Who will get rid of the EXEC SQL so that your program can be compiled? </li></ul><ul><li>.The PRECOMPILER(PC) will replace the delimiter flags with CALLS </li></ul><ul><li>Ii will also verify whether </li></ul><ul><ul><li>-Your SQL statements are correct </li></ul></ul><ul><ul><li>-Your host variables match the db2 datatypes </li></ul></ul><ul><ul><li>NOT access DB2 </li></ul></ul><ul><li>EXEC SQL DECLARE TABLE </li></ul><ul><li>EXEC SQL </li></ul><ul><li>DECLARE EDUCS99.EMP99 TABLE </li></ul><ul><li>(EMPNO CHAR(6) NOT NULL, </li></ul><ul><li>LASTNAME . . .) </li></ul><ul><li>END EXEC. </li></ul>声明 TABLE 结构 DB2 Embedded SQL -- Program Preparation
  183. 184. Declaration Generator DCLGEN creates source code output that it stores as a member of a Partitioned Data Set (PDS). You can use this output in place of coding table declarations and host variables. DCLGEN can save you time coding and, because DCLGEN extracts the information to create host variables definitions directly from the DB2 catalog, you can be sure those definitions are accurate. DVLP.BOOKLIB(EMPXXRCD) Embedded SQL -- DCLGEN
  184. 185. In DCLGEN Panel you provide three types of information: 1. Identify table you want to create host variables for 2. Name the output data set that will hold the declarations DCLGEN will produce. 3. Specify processing options for the DCLGEN run. To Use DCLGEN , select option 2 from the DB2I Primary Option Menu. EMP99 EDUCS99 ‘ DVLP.BOOKLIB(EMP99RCD)’ EMP99DCL Embedded SQL -- DCLGEN
  185. 186. Option 1 : SOURCE TABLE NAME The name of the base table that you would like to make a table declaration and host variables for. Option 2 : TABLE OWNER (optional) The name of the owner of the table (if table is not your own) Option 3 : AT LOCATION (optional) This is the location of the source table specified in option 1. If no location is given, the default location is used. This is normally omitted. EMP99 DVLP Embedded SQL -- DCLGEN
  186. 187. Option 4: DATA SET NAME Here you specify the name of the output data set that will hold the declarations. It can be a sequential data set or a member of a pre-existing PDS. Sequential data sets should have 80-character records and must exist before you run DCLGEN . You can create a new partitioned data set member with DCLGEN as long as the library that will hold the member already exists. Option 5 : DATA SET PASSWORD If the data set has a password, specify it here. ‘ DVLP.BOOLIB(EMP99RCD)’ Embedded SQL -- DCLGEN
  187. 188. Option 6 : ACTION Specifies what DCLGEN will do if library member already in use. ADD -- DCLGEN only allows you to add a new member to the destination data set. REPLACE -- DCLGEN will delete old library member, if exists, and create new one. (normally used) Embedded SQL -- DCLGEN
  188. 189. Option 7 : COLUMN LABEL By specifying ‘YES’, DCLGEN is caused to include values DBA coded with LABELS ON statement. These labels are added as comments to the DCLGEN output. Option 8 : STRUCTURE NAME Uses the specified name as the group name for the host variables items. If you leave this option blank, DCLGEN will append the name of the table to ‘DCL’. DCLGEN uses the name of the columns in the table as the names for the host variables. EMP99DCL Embedded SQL -- DCLGEN
  189. 190. Option 9 : FIELD NAME PREFIX Specifies an up to 28 character long string that will be concatenated with a different number for each column to be used for the column name. The original names of the columns are included in the output, but only as comments. This is normally left blank. EMP99DCL Embedded SQL -- DCLGEN
  190. 191. The PRECOMPILE- Functions <ul><li>Includes DCLGEN members </li></ul><ul><li>Includes SQLCA </li></ul><ul><li>Looks for SQL statements and for the definition of host variables </li></ul><ul><li>Verifies SQL syntax </li></ul><ul><li>Matches each column and table name in the SQL to the DECLARE TABLE statements </li></ul><ul><li>Prepares the SQL for compilation or assembly in the host language </li></ul><ul><li>Produces a DBRM and stores it in a PDS user's library </li></ul><ul><li>Can be invoked in DB2I or batch </li></ul><ul><li>DOES NOT ACCESS DB2 </li></ul>DB2 Embedded SQL -- Program Preparation
  191. 192. SQL INCLUDE Statement <ul><li>INCLUDE member-name </li></ul><ul><ul><li>used to include DCLGEN output </li></ul></ul><ul><ul><li>Nested INCLUDE not allowed </li></ul></ul><ul><ul><li>Any source can be included </li></ul></ul>Cobol program code: EXEC SQL INCLUDE EMP99RCD END EXEC. PAGE:3-24
  192. 193. SQL Communication Area - SQLCA SQL Stmt SQLCA Program checks returned values Execute SQL stmt and Updates the Comm Area Program DB2 SQLCODE
  193. 194. SQL INCLUDE SQLCA Statement Used to Include SQLCA declaration <ul><li>Cobol program code: </li></ul><ul><ul><li>EXEC SQL </li></ul></ul><ul><ul><li>INCLUDE SQLCA </li></ul></ul><ul><ul><li>END EXEC. </li></ul></ul>The precompiler generate an SQLCA in your program
  194. 195. 01 SQLCA. 05 SQLCAID PIC X(8). 05 SQLCABC PIC S9(9) COMP-4. 05 SQLCODE PIC S9(9) COMP-4. 05 SQLERRM. 49 SQLERRML PIC S9(4) COMP-4. 49 SQLERRMC PIC X(70). 05 SQLERRP PIC X(8). 05 SQLERRD OCCURS 6 TIMES PIC S9(9) COMP-4. 05 SQLWARN. 10 SQLWARN0 PIC X. 10 SQLWARN1 PIC X. 10 SQLWARN2 PIC X. 10 SQLWARN3 PIC X. 10 SQLWARN4 PIC X. 10 SQLWARN5 PIC X. 10 SQLWARN6 PIC X. 10 SQLWARN7 PIC X. 05 SQLEXT PIC X(8). Embedded SQL -- SQLCA
  195. 196. The DB2 precompiler produces a DBRM (DataBase Request Module) and a modified source program with the SQL statements commented out. The DB2 BIND command turns a DBRM into an executable format. The DB2 Catalog stores information about the plan and package. DB2 Directory stores the actual plan and package. DB2 Embedded SQL -- Program Preparation
  196. 197. <ul><li>DBRM : </li></ul><ul><li>D ata B ase R equest M odule is a module containing SQL statements extracted from a source program by the DB2 precompiler. It is stored as a member of a partitioned data set. It is NOT stored in the DB2 catalog or DB2 directory. </li></ul><ul><li>A DBRM </li></ul><ul><li>Contains extracted , parsed SQL source </li></ul><ul><li>Is stored as a member in a partitioned dataset </li></ul><ul><li>One member created per precompile </li></ul><ul><li>Will become input to BIND </li></ul>DVLP.DBRM Program Preparation-Precompile
  197. 198. When a DBRM is bound into a plan , all its SQL statements are placed into the SYSIBM.SYSSTMT DB2 Catalog table. When a DBRM is bound into a package , all its SQL statements are placed into the SYSIBM.SYSPACKSTMT table. One DBRM corresponds to exactly one source module. Program Preparation-Precompile
  198. 199. Modify Source Precompiler replaced the SQL statements with a CALL to module DSNHLI (High Level Language Interface) . In COBOL, SQL-TIMESTAMP-1 and SQL-TIMESTAMP-2 represent the upper and lower portions of the modified store-clock value. The value of SQL-STMT-NUM corresponds with the statement numbers of the precomplier listing. Although often call a timestamp, SQL-TIMESTAMP-1 and SQL-TIMESTAMP-2 make up the consistency token, which is a modified store-clock value(not to be confused with the timestamp data type). COBOL’s two-part timestamp is due to its lack of support, at the time, for a 32-bit binary data field. Program Preparation-Precompile
  199. 200. <ul><li>Modify Source </li></ul><ul><li>CALL DSNHLI parameters: </li></ul><ul><ul><li>DBRM name(SQL-PROG-NAME) </li></ul></ul><ul><ul><li>Timestamp(SQL-TIMESTAMP-1,SQL-TIMESTAMP-2) </li></ul></ul><ul><ul><li>Statement Number(SQL-STMT-NUM) </li></ul></ul><ul><li>Other parameters: </li></ul><ul><ul><li>Addresses of host variables </li></ul></ul><ul><ul><li>Addresses of SQLCA </li></ul></ul><ul><li>At this stage,the two components, DBRM and modified source, will part and won’t see each other again until program execution. </li></ul><ul><li>Therefore, the call must include all necessary information for db2 to be able to locate the access path needed to execute the SQL statement associated with the call. </li></ul>Program Preparation-Precompile
  200. 201. <ul><li>After precompilation ,you have to compile and link-edit </li></ul><ul><li>--This can be done using: </li></ul><ul><li>.DB2I panels </li></ul><ul><li>.JCL </li></ul><ul><li>CICS COMMAND TRANSLATOR may have to be invoked </li></ul>The link-edit will have to include the necessary modules for the call to work properly. OS/390 Supports many execution enviroments:TSO,CICS,IMS, and so forth. In the link-edit step different interface modules will have to be included. They have the same entry point:DSNHLI. Compilation and LINK-EDIT
  201. 202. BIND PACKAGE runs in TSO(Online or Batch) BIND PACKAGE creates a package in the DB2 directory <ul><li>FUNCTIONS: </li></ul><ul><ul><li>Validates SQL </li></ul></ul><ul><ul><li>Resolves table names </li></ul></ul><ul><ul><li>checks privileges </li></ul></ul><ul><ul><li>chooses an access path based on catalog statistics </li></ul></ul><ul><ul><li>stores source SQL in catalog </li></ul></ul><ul><ul><li>stores executable access path(PACKAGE) in DB2 directory </li></ul></ul>Page:3-38 BIND PACKAGE
  202. 203. Package: A package is a single, bound DBRM with optimized access paths. By using packages, the table access logic is “packaged” at a lower level of granularity, at the package or program level. To execute a package, it must be included in the package list of a plan. Packages are NEVER directly executed--they are ONLY indirectly executed when the plan in which they are contained executes. When a package is bound, DB2 access the following tables: SYSIBM.SYSCOLDIST SYSIBM.SYSCOLDISTATATS SYSIBM.SYSCOLSTATS SYSIBM.SYSCOLUMNS SYSIBM.SYSINDEXES SYSIBM.INDEXSTATS SYSIBM.PACKAGE SYSIBM.SYSPACKAUTH SYSIBM.SYSPACKAUTH SYSIBM.SYSTABLES SYSIBM.SYSTABLESPACE SYSIBM.SYSTABSTATS SYSIBM.SYSUSERAUTH Information about packages is stored in the following tables: SYSIBM.SYSPACKAGE SYSIBM.SYSPACKAUTH SYSIBM.SYSPACKDEP SYSIBM.SYSPACKSTMT SYSIBM.SYSPKSYSTEM SYSIBM.SYSTABAUTH DB2 Embedded SQL -- Program Preparation
  203. 204. DBRM BIND PACKE(collx) MEMBER(dbrma) BIND PACKE(colly) MEMBER(dbrma) colly dbrma dbrmb Dbrm... Package name= collection_id.package_id PACKAGE collx dbrma dbrmb Dbrm...
  204. 205. A collection is a set of packages. A package is bound in a collecion. A collection is implicitly created at first BIND PACKAGE referring to that collection. Example: BIND PACKAGE( online ) MEMBER(pkg1) BIND PACKAGE( batch ) MEMBER(pkg3) Collection(packageset) online pkg1 pkg2 batch pkg3 pkg4
  205. 206. A package can be bound in multi collecions in a single DB2 system. Example: BIND PACKAGE(test_payroll) MEMBER(pkg1) BIND PACKAGE(prod_payroll) MEMBER(pkg1) Collection(packageset) test_payroll pkg1 pkg2 prod_payroll pkg1 pkg3
  206. 207. Mprog1 call DSNHLI ( dbrm1 ,  ,1) ... call DSNHLI ( dbrm1 ,  ,2) ... Mprog1 ... call DSNHLI ( dbrm2 ,  ,1) ... Call  Call  call  DB2 Directory colly dbrm1  ? Page:3-44 Locating PACKAGEs at execution time collx dbrm1  dbrm3  collz dbrm2  dbrm4 
  207. 208. Mprog1 call DSNHLI ( dbrm1 ,  ,1) ... call DSNHLI ( dbrm1 ,  ,2) ... Mprog2 ... call DSNHLI ( dbrm2 ,  ,1) ... Call  Call  call  DB2 Directory colly dbrm1  Page:3-44 Collx.dbrm1,collz.* plana BIND PLAN(plana) Pklist(Collx.dbrm1,collz.*) Locating PACKAGEs at execution time collx dbrm1  dbrm3  collz dbrm2  dbrm4 
  208. 209. How does DB2 find the right package with the right timestamp? Several packages exist in different collections with the same timestamp(different BIND PACKEGE with same input DBRM), which package will DB2 use? There is a missing link. Locating PACKAGEs at execution time
  209. 210. PLAN :An additional structure that will guide DB2 in its search for the appropriate package. A package can only be located and executed via a PLAN A PLAN contains a PACKAGE LIST , a list of logical pointers to packages which makes specific parts of the directory eligible for the packake search. The dbrm name and the timestamp provided with the call is used to locate the correct package via the package list. DB2 will look for the right(same timestamp) package by going through each entry in the package list in turn until it has a hit. Running a DB2 program is done by associating the plan with the load module. This is done outside the program. RUN PROGRAM( mprog1 ) PLAN( plana ) PLAN and PACKAGEs
  210. 211. Plans are created by the BIND PLAN command. BIND PLAN(plana) PKLIST(Collx.dbrm1,collz.*) When a plan is bound, DB2 reads the following DB2 catalog tables: SYSIBM.SYSCOLDIST SYSIBM.SYSCOLDISTSTATS SYSIBM.SYSCOLSTATS SYSIBM.SYSCOLUMNS SYSIBM.SYSINDEXES SYSIBM.SYSINDEXSTATS SYSIBM.SYSPLAN SYSIBM.SYSPLANAUTH SYSIBM.SYSTABLES SYSIBM.SYSTABLESPACE SYSIBM.SYSTABSTATS SYSIBM.SYSUSERAUTH Information about plans is then stored in the following tables: SYSIBM.SYSDBRM SYSIBM.SYSPACKAUTH SYSIBM.SYSPACKLIST SYSIBM.SYSPLAN SYSIBM.SYSPLANAUTH SYSIBM.SYSPLANDEP SYSIBM.SYSPLSYSTEM SYSIBM.SYSSTMT SYSIBM.SYSTABAUTH PLAN and PACKAGEs
  211. 212. BIND PLAN(plana) PKLIST(Collx.dbrm1,collz.*) BIND PLAN(plana) PKLIST(Collx.dbrm1,collz.*) MEMBER(dbrma,dbrm1) BIND PLAN(plana) MEMBER(dbrma,dbrm1) collx.dbrm1,collz.* plana collx.dbrm1,collz.* planb dbrma  dbrm1  planc dbrm1  dbrm2   Instream DBRM BIND PLAN - DBRMS
  212. 213. collx.dbrm1,collz.* plana collx.dbrm1,collz.* planb dbrma  dbrm1  planc dbrm1  dbrm2  ... CALL DSNHLI(dbrm1,  ,1) ... Instream DBRM first! PACKAGE Search
  213. 214. collx.dbrm1,colly.* plana collx.dbrm1,colly.* planb dbrma  dbrm1  planc dbrm1  dbrm2  ... CALL DSNHLI(dbrm1,  ,1) ... Sqlcode: -818 Sqlcode: -805 colly dbrm1  Timestamp Mismatch Errors
  214. 215. TSO RUN PROGRAM( mprog1 ) PLAN( plana ) CICS RCT(Resource Control Table) IMS RTT(Resource Translate Table) CAF Callable Interface(DSNALI) RRSAF DSNRLI Running the Program
  215. 216. Each execution environment has its own language interface LINK-EDIT
  216. 217. ... SELECT ... FROM TAB1 ... dbrm BIND PACKAGE QUAL(TEST) BIND PACKAGE QUAL(PROD) BIND PACKAGE TEST .TAB1 binder .TAB1 PROD .TAB1 binder BIND PACKAGE OR PLAN BIND - QUALIFIER Option
  217. 218. ... SELECT ... FROM TAB1 ... dbrm BIND PACKAGE(usdcol) QUAL(usd) USD .TAB1 YEN .TAB1 dbrm1  usdcol BIND PACKAGE(yencol) QUAL(yen) dbrm1  yencol Same structure TABLE Mirroring-1
  218. 219. ... SELECT ... FROM TAB1 ...  USD .TAB1 YEN .TAB1 dbrm1  usdcol BIND PLAN(plan1) Pklist(usdcol.*,yencol.*) dbrm1  yencol lmod1 usdcol.*, yencol.* plan1 TABLE Mirroring-2
  219. 220. coll = ‘yencol’ . SET CURRENT PACKAGESET=:coll . SELECT ... FROM TAB1  USD .TAB1 YEN .TAB1 dbrm1  usdcol BIND PLAN(plan1) Pklist(usdcol.*,yencol.*) dbrm1  yencol lmod1 usdcol.*, yencol.* plan1 TABLE Mirroring-3
  220. 221. CURRENT PACKAGESET Blank First look at all DBRMs in PLAN then look at collections not blank Only look in the specified collection, disregard DBRMs or any other collection EXEC SQL SET CURRENT PACKAGESET = ‘COL1’ SET CURRENT PACKAGESET will activate only the entries in the package list that refer to that particular collection Special Register- CURRENT PACKAGESET
  221. 222. pgma  UTTEST.SRC Precompile version (uttest) Precompile version (systest) pgma  UTTEST.LOAD pgma  SYSTEST.LOAD BIND PACKAGE(collx) MEMBER(pgma) pgma  collx pgma  pgma  UTTEST.SRC PACKAGE VERSIONING
  222. 223. RR (Repeatable Read) The contens of a data row or page will not change until the program commits. With the RR , all row(page) locks are held as the data is accessed. Locks are held on all rows that are touched, even no-qualifying rows(not meet all WHRERE conditions). They are not released until the next commit point . This locks out all other application processes from accessing these rows or pages, guaranteeing the consistency of the data, until the commit point . A row ‘touched’ by the program will remain unchanged until the user COMMIT S or ROLLBACK S.If the same SELECT is repeated within the same LUW , you would get the same exact answer set. Although RR ensures the data consistency, it is very restrictive for those applications that need concurrent access to the data. Data Consistency- Isolation Level
  223. 224. CS (Cursor Stability) When a data row is read by a program, its contents are available for update by other programs as soon as the data access is finished. That is, a row ‘read’ is released as soon as the data is read. This option allows for maximum concurrency, but additional logic will be needed in the program( REFRESH ). Data Consistency-Isolation Level
  224. 225. RS (Read Stability) DB2 takes a lock on the row or page it accesses but only holds those locks where the rows satisfy the WHERE conditions, permmitting more concurrency than RR. Locks on the qualifying rows are held until the program issues a commit. No other application process can update or delete a row that is part of the answer set. Thus your update can be performed without consistency problems. However, it is possible that more row s can be inserted into table or no-qualifying rows can be updated to satisfy the original WHERE conditions. If the same SELECT is repeated within the same LUW, you might not get the same answer set. Data Consistency-Isolation Level
  225. 226. UR(Uncommitted Read) READ without integrity check. UR is applicable in those cases where the statement is read-only and where there is no risk for an integrity exposure. Isolation UR has some powerful capabilities as it is able to read through locks. However, it should be used with great care since it can cause serious consistency problems. All of these isolation levels can be set at the statement, package, or plan level. Data Consistency-Isolation Level
  226. 227. Conclusions: 1. Modified data is always hidden until the modifier commits unless you specify UR. 2. If you specify isolation(RR or RS), read data will additionally BE PROTECTED AGAINST UPDATES until the reader commits. Commit as soon as possible after updates. Don’t use RR but re-read the data instead before or during the update operation. If you want to protect qualifying data that has been read, you should use RS instead of RR. Data Consistency-Isolation Level
  227. 228. Package benefits : 1. Reduced bind time. If packages are NOT used when multiple DBRMs are bound into a plan and the SQL within one of those programs changes, the entire plan must be rebound. 2. Smaller granularity of bind parameters. Bind options can be specified at the program level. 3. Versioning. Packages can be versioned, thus enabling multiple versions of the same package existing at the same time in the DB2 catalog. Simply by running the appropriate load module, DB2 chooses the correct package to execute. DB2 uses a package selection algorithm to execute the correct access path. DB2 Embedded SQL -- Program Preparation
  228. 229. TSO SQL FREE PLAN(plan-id,...) FREE PACKAGE(collection-id. package-id(version-id)) DROP PACKAGE collection-id.package-id VERSION version-id Deleting a package or plan from the DB2 system FREE / DROP
  229. 230. Source Program DCLGEN Precompiler DBRM Bind Package Package Plan DB2 Catalog DB2 Directory Modified Source(SQL) Compiler Compiled Source Linkage Editor Load Module CICS TRANSLATE Modified Source EXEC SQL 转换成 CALL 语句 EXEC CICS 转换成 CALL 语句 Plan Package Package Package Package Package Package <ul><li>一 个 Package 一个程序 </li></ul><ul><li>每个 Package 包括 Access Path </li></ul>translate ispf editer dclgen Program Preparation-Summary Version level
  230. 231. DB2 AND COBOL DB2 & COBOL
  231. 232. DB2 Programming Concept DB2 Ap p l i c a t i o n S t r u c t u r e DB2 Ap p l i c a t i o n S t r u c t u r e ․ WORKING STORAGE SECTION - INCLUDE TABLE STRUCTURE - INCLUDE SQLCA - CURSOR DECLARATION ․ PROCEDURE DIVISION - ERROR HANDLING - DML SQL STATEMENT - CURSOR HANDLING - CHECK SQLCODE
  232. 233. Two types or embedded SQL statements: 1. Singleton SELECTs -- MUST select only ONE row. And MUST contain INTO clause. Here the names of the host variables that will accept the data returned by DB2 are listed. 2. Cursor SELECTs -- Processes multiple rows. Embedded SQL
  233. 234. <ul><li>Each statement must begin with EXEC SQL and end </li></ul><ul><li>with END-EXEC: </li></ul><ul><li>EXEC SQL </li></ul><ul><li>INCLUDE CUSTRCD </li></ul><ul><li>END-EXEC. </li></ul><ul><li>All SQL statements must be coded in columns 12 - 72. </li></ul><ul><li>To continue text from one line to another, code as much of the </li></ul><ul><li>string as you can on the first line, then on subsequent lines, the first </li></ul><ul><li>non-blank character needs to be a quotation mark. </li></ul><ul><li>When you have reached the end of the string, code a closing </li></ul><ul><li>quotation mark. (Whether or not to use single or double quotation </li></ul><ul><li>marks depends on the options you use for the DB2 pre-compiler.) </li></ul>Embedded SQL- SQL Coding Rules
  234. 235. <ul><li>Don’t code an SQL statement in a COBOL Copy member. </li></ul><ul><li>When one SQL statement immediately follows another, always code a period after the first’s END-EXEC </li></ul>EXEC SQL INCLUDE CUST END-EXEC. EXEC SQL INCLUDE SQLCA END-EXEC. Embedded SQL- SQL Coding Rules
  235. 236. What you DON’T code for a DB2 Table: 1. A COBOL SELECT statement 2. A File Description entry 3. A Record Description What you DO or CAN code: 1. INCLUDE statement for SQL Communications Area 2. Table Declarations 3. Host Variables 4. Cursors Embedded SQL
  236. 237. <ul><li>SQL Communications Area: </li></ul><ul><li>SQLCA is a set of fields through which DB2 passes back information about the success of an executed SQL statement. </li></ul><ul><li>SQLCA must be defined in each DB2 COBOL program. </li></ul><ul><li>To have the precompiler include the SQLCA fields in your </li></ul><ul><li>program code the following in your WORKING-STORAGE section: </li></ul><ul><li> EXEC SQL </li></ul><ul><li>INCLUDE SQLCA </li></ul><ul><li> END-EXEC. </li></ul>Embedded SQL -- SQLCA
  237. 238. 01 SQLCA. 05 SQLCAID PIC X(8). 05 SQLCABC PIC S9(9) COMP-4. 05 SQLCODE PIC S9(9) COMP-4. 05 SQLERRM. 49 SQLERRML PIC S9(4) COMP-4. 49 SQLERRMC PIC X(70). 05 SQLERRP PIC X(8). 05 SQLERRD OCCURS 6 TIMES PIC S9(9) COMP-4. 05 SQLWARN. 10 SQLWARN0 PIC X. 10 SQLWARN1 PIC X. 10 SQLWARN2 PIC X. 10 SQLWARN3 PIC X. 10 SQLWARN4 PIC X. 10 SQLWARN5 PIC X. 10 SQLWARN6 PIC X. 10 SQLWARN7 PIC X. 05 SQLEXT PIC X(8). Embedded SQL -- SQLCA
  238. 239. <ul><li>The most important field in the SQLCA is the SQLCODE which is DB2’s return code field. </li></ul><ul><li>SQLCODE values: </li></ul><ul><li>Zero (0) -- Execution successful </li></ul><ul><li>Positive -- Statement successful, but with some exceptional condition </li></ul><ul><li>+100 -- Row not found or end of data </li></ul><ul><li>Negative -- Serious error detected (Statement failed) </li></ul><ul><li>You want to check the SQLCODE after every EXEC SQL you code to be sure that the SQL statement was successful. </li></ul>Embedded SQL -- SQLCA
  239. 240. <ul><li>SQLSTATE is a cross-platform SQL return code contained in a 5 digit character string. </li></ul><ul><li>SQLSTATE values: </li></ul><ul><ul><ul><li>‘ 00000’ success </li></ul></ul></ul><ul><ul><ul><li>‘ 01ddd’ warning </li></ul></ul></ul><ul><ul><ul><li>‘ 02000’ not found </li></ul></ul></ul><ul><ul><ul><li>‘ else’ error </li></ul></ul></ul><ul><li>Recommended that: </li></ul><ul><li>you use SQLSTATE instead of SQLCODE </li></ul>Embedded SQL -- SQLCA
  240. 241. Table Declarations are not required but do offer good documentation. Also, when table declarations are present, the DB2 pre-compiler uses it to verify errors that might otherwise get through. Table declarations should be coded in WORKING-STORAGE The following code declares the table PERSON: EXEC SQL DECLARE PERSON TABLE ( SSN CHAR(9) NOT NULL, FNAME CHAR(10) NOT NULL, LNAME CHAR(10) NOT NULL, ADDRESS CHAR(20), CITY CHAR(12), STATE CHAR(2), ZIP CHAR(5), PHONE CHAR(10) ) END-EXEC. Embedded SQL -- Table Declarations
  241. 242. Host Variables are fields that DB2 uses to move data to and from your program and a table. You can define host variables in DATA DIVISION’s WORKING-STORAGE OR LINKAGE SECTION . You would code host variables as a level 10 variable. For example, FNAME CHAR(10) NOT NULL is the table declaration of FNAME. A host variable to FNAME would be: 10 FNAME PIC X(10) Embedded SQL -- Host Variables
  242. 243. Level - 01 items are called host structures. A host structure is a named set of elementary items. With DB2 you can only create host structures with two levels, for relational tables are two-dimensional, with no structures nested inside other structures. DB2 doesn’t support repeating groups. So there will be NO OCCURS clause in any host variable definitions. There are 7 basic data types for data in DB2 tables: 1. CHAR 5. DATE 2. SMALLINT 6. TIME 3. INTEGER 7. TIMESTAMP 4. DECIMAL Embedded SQL -- Host Structures
  243. 244. Basic Data types Typical COBOL Definition CHAR 10 CITY PIC X(20). character (EBCDIC) data SMALLINT 10 SMALL-CNT PIC S9(4) COMP. Halfword integer data INTEGER 10 LARGE-CNT PIC S9(9) COMP. Fullword integer data DECIMAL 10 INVOICE-TOTAL PIC S9(7)V99 COMP-3. Packed-decimal data DATE 10 INVOICE-DATE PIC X(10). Date Data (yyyy-mm-dd) TIME 10 INVOICE-TIME PIC X(8). Time data (hh.mm.ss) TIMESTAMP 10 INVOICE-TIMESTAMP PIC X(26). Date and time data, with microseconds (yyyy-mm-dd-hh.mm.ss.mmmmmm) Embedded SQL -- Data Types
  244. 245. When using host variables in SQL statements, you must precede the host variable name with a colon( : ). Example: EXEC SQL SELECT FNAME, LNAME, ADDRESS INTO :FNAME, :LNAME, :ADDR FROM PERSON WHERE PERSON.SSN = :SSN END-EXEC. When executed FNAME, LNAME, and ADDRESS items will be put into the host variables FNAME, LNAME, and ADDR (respectfully) from the tuple in PERSON table, whose SSN matches the one in the host variable SSN. Embedded SQL -- Host Variable
  245. 246. In order to be able to process a results table that contains more than one row, you have to use cursors . A cursor is a pointer that identifies the current row in a results table. A cursor can only point to one row at a time. - Is required for SELECT of multiple rows - Is never used for INSERT - May be reused (CLOSED + new OPEN) - Will be close at COMMIT unless declared with WITH HOLD Muliple cursors: - May be defined in a program - May work with the same table - May be open simultaneously Embedded SQL -- Cursors
  246. 247. There are four steps in using a cursor: 1. Use DECLARE CURSOR to specify a cursor for result table. 2. Issue OPEN statement to begin cursor processing. 3. Issue one FETCH statement for each row in result table. 4. Conclude cursor processing by issuing CLOSE statement. Embedded SQL -- Cursors
  247. 248. Processing Multiple Rows EMPNO LASTNAME 000030 000290 000300 KWAN PARKER SMITH . DEFINE a CURSOR EXEC SQL DECLARE K9 CURSOR FOR SELECT EMPNO, LASTNAME FROM TEMPL WHERE DEPTNO = :DPT END-EXEC. . OPEN the CURSOR EXEC SQL OPEN K9 END-EXEC. . FETCH RESULT ROWS ONE AT A TIME EXEC SQL FETCH K9 INTO :EMPNO, :NAME END-EXEC. . CLOSE CURSOR when finished EXEC SQL CLOSE K9 END-EXEC. Loop until break Embedded SQL -- Cursors
  248. 249. DECLARE CURSOR specifies what the results table should contain. It contains a SELECT statement where you name the columns you want to retrieve, the table that contains them, and the selection conditions for them. Example: DECLARE CURSOR for retrieving instructor information for a course. EXEC SQL DECLARE INSTCURS CURSOR FOR SELECT DISTINCT PERSON.FNAME, PERSON.LNAME, OFFICE#, OFFICE_PHONE# FROM PERSON, TEACHER, SECTION WHERE SECTION.COURSE# = :COURSE-NUM AND PERSON.SSN = TEACHER.SSN AND SECTION .SSN = PERSON END-EXEC. CURSORS -- DECLARE CURSOR
  249. 250. DECLARE CURSOR : DECLARE CURSOR can be coded in WORKING-STORAGE or PROCEDURE DIVISION . There are no INTO clauses in a DECLARE CURSOR’s SELECT statement. Only need to declare a cursor once. DB2 does not create the results table until SQL OPEN statement is executed for the table’s cursor. CURSORS -- DECLARE CURSOR
  250. 251. DECLARE CURSOR : The SELECT statement in the DECLARE CURSOR statement simply specifies the characteristics of the result table that will be associated with the cursor. Coding DISTINCT keyword in the SELECT component of a DECLARE CURSOR statement directs DB2 to exclude duplicate rows from the results table. ORDER-BY statement allows you to sort the result table. CURSORS -- DECLARE CURSOR
  251. 252. Opening a cursor: OPEN statement generates the results table associated with the cursor and positions the cursor just before the first row of the table. EXEC SQL OPEN INSTCURS END-EXEC. OPEN is coded in the PROCEDURE DIVISION . Embedded SQL -- Cursors
  252. 253. Closing a Cursor CLOSE statement releases the results table associated with the specified cursor. EXEC SQL CLOSE INSTCURS END-EXEC. Closing a table is not required, since DB2 automatically closes all tables when the program ends. However, closing a table yourself allows you to release a substantial amount of memory the table uses and it allows you to re-open a table with out ending the program. Embedded SQL -- Cursors
  253. 254. Retrieving a row from a cursor-controlled results table: Use the FETCH statement to retrieve a row from a results table that has a cursor. EXEC SQL FETCH INSTCURS INTO :FNAME, :LNAME, :OFFICE#, :OFFICE_PHONE# END-EXEC. Evaluate the SQLCODE after each FETCH . When SQLCODE equals +100, you have reached the end of the result table (similar to end of file). Embedded SQL -- Cursors
  254. 255. EXEC SQL DECLARE CE CURSOR FOR SELECT...FROM EMP99; WHERE ... : : EXEC SQL OPEN CE; EXEC SQL FETCH CE INTO...: EXEC SQL DELETE FROM EMP99 WHERE CURRENT OF CE; : : EXEC SQL CLOSE CE: Cursors-- DELETE via a CURSOR
  255. 256. EXEC SQL DECLARE CX CURSOR FOR SELECT EMPNO, LASTNAME FROM EMP99 WHERE DEPTNO = :DPT FOR UPDATE OF LASTNAME END-EXEC. : EXEC SQL OPEN CX END-EXEC. EXEC SQL FETCH CX INTO :EMPNO, :NAME END-EXEC. EXEC SQL UPDATE EMP99 SET LASTNAME = :NEWNAME WHERE CURRENT OF CX END-EXEC. : EXEC SQL CLOSE CX END-EXEC. Cursors-- UPDATE via a CURSOR
  256. 257. - Indicates successful end of a unit of work - Changes to data will be written - All PAGE LOCKS released - TABLE(SPACE) LOCKS released if RELEASE (COMMIT) on BIND - CURSOR CLOSED COMMIT Embedded SQL -- Cursors
  257. 258. COMMIT - CURSOR REPOSITIONING EXEC SQL DECLARE C1 CURSOR FOR SELECT X,Y,Z FROM T1 WHERE X >:STORX; : STORX = ' '; S0:CTR = 0; S1:EXEC SQL OPEN C1; S2:EXEC SQL FETCH C1 INTO :STORX,:STORY,:STORZ; /* If no update on this row, loop to S2 */ S3:EXEC SQL UPDATE T1 SET Y = :NEWY, Z = :NEWZ WHERE X = :STORX; UPDATE current row CTR = CTR+1; IF CTR < 500 THEN GO TO S2; ELSE EXEC SQL COMMIT; GO TO S0; Cursors-- CURSOR REPOSITIONING
  258. 259. <ul><li>Read-Only Cursors: </li></ul><ul><ul><li>The SELECT statement contains : - FOR FETCH ONLY / FOR READ ONLY - ORDER BY; UNION or UNION ALL </li></ul></ul><ul><ul><li>The first SELECT contains - DISTINCT; a FUNCTION or EXPRESSION </li></ul></ul><ul><ul><li>The outer subselect contains GROUP BY / HAVING </li></ul></ul><ul><ul><li>The same table is used in SELECT statement and SUBQUERY </li></ul></ul><ul><ul><li>Select from multiple tables(join) </li></ul></ul><ul><ul><li>A nested table expression is used in the first FROM </li></ul></ul><ul><ul><li>Isolation UR is used without FOR UPDATE OF </li></ul></ul>UR + FOR UPDATE OF = CS Cursors-- Read-Only CURSORS
  259. 260. EXEC SQL DECLARE C1 CURSOR FOR SELECT . . . OPTIMIZE FOR 20 ROWS END-EXEC. Used in online environment. Used to Improve performance. It is only used during the access path determination. It can NOT solve all your access performance problems. Cursors-- Optimize for n Rows
  260. 261. EXEC SQL DECLARE C1 CURSOR FOR SELECT . . . WITH RR/RS/CS/UR END-EXEC. <ul><li>Allows the override of package/plan isolation </li></ul><ul><li>UR + FOR UPDATE OF = CS </li></ul><ul><li>Can be used on a simple SELECT INTO </li></ul>Cursors-- with RR/RS/CS/UR
  261. 262. EXEC SQL DECLARE C1 CURSOR FOR SELECT . . . WITH RR/RS KEEP UPDATE LOCKS END-EXEC. <ul><li>Maintain X-lock(exclusive) on row/page even if the row was not updated </li></ul><ul><li>Might reduce the possibilty of a deadlock </li></ul><ul><li>If not used properly, it could reduce the degree of concurrency </li></ul>Cursors-- keep update locks
  262. 263. SELECT statement In PROCEDURE DIVISION: EXEC SQL SELECT column-specification, [ column-specification, … ] INTO : host-var, [: host-var… ] : host-structure FROM table-name, [ table-name,… ] [ WHERE selection-condition ] END-SQL. Embedded SQL -- Select
  263. 264. column-specification A description of what the SELECT statement should put in the corresponding results table EXEC SQL SELECT column-specification, [ column-specification, … ] Embedded SQL -- Select
  264. 265. host-var The COBOL host variable name into which DB2 will put the data for the corresponding column-specification. Note that the host variable name is preceded by a colon. INTO : host-var, [: host-var… ] : host-structure host structure The COBOL name of the group item into which DB2 will place the data it retrieves from the table. Embedded SQL -- Select
  265. 266. selection-condition Specifies a test that SQL will apply to each row in the table to determine whether to include it in the results table. [ WHERE selection-condition ] Embedded SQL -- Select
  266. 267. Example: Say you have the following FNAME data in the person table: BOB GREEN MARY WHITE JANE SMITH To return the first and last name of a person with the first name “BOB”, you execute the statement: EXEC SQL SELECT LNAME, FNAME INTO :LNAME, FNAME FROM PERSON WHERE FNAME = ‘BOB’ END-EXEC. When this SQL statement executes, it returns a one row results table: BOB GREEN Embedded SQL -- Select
  267. 268. What if you had multiple “BOB”s and wanted to print them all? Then you would use a cursor defined as follows: EXEC SQL DECLARE NAMEINFO CURSOR FOR SELECT FNAME, LNAME FROM PERSON WHERE FNAME = “BOB” END-EXEC. Then your SQL statement would be: EXEC SQL FETCH NAMEINFO INTO :FNAME, :LNAME END-EXEC. Embedded SQL -- Select
  268. 269. Ways to specify values for a results table in the SELECT clause 1. Unqualified column name. SELECT FNAME, LNAME 2. Qualified column name. SELECT PERSON.LNAME, MANAGER.LNAME 3. * -- All columns from a qualified source. SELECT * 4. Host variables. SELECT LNAME, FNAME, :COURSE# Embedded SQL -- Select
  269. 270. 5. Literals. SELECT LNAME, FNAME , “is an Illinois resident.” Adds the literal to the results table. 6. Computed Values. (shown on next slide) 7. USER keyword SELECT USER Extracts the current user id from the DB2 catalog and adds it to the results table. Embedded SQL -- Select
  270. 271. Computed Values. Arithmetic expressions -- use a combination of host variables, column values and literals connected to each other with operators. The result is stored in the corresponding column of the results table. ** All items in arithmetic expressions must be numeric . ** SELECT LNAME, SALARY - :TAX Character data -- you can only combine, concatenate, two or more base table columns using the || symbol. SELECT FNAME || LNAME || ADDR || CITY || STATE || ZIP Length of resulting column is the sum of lengths of elements. Embedded SQL -- Select
  271. 272. FROM clause The FROM clause specifies which base tables to include in the SQL processing. When two or more tables have a common column name, say SSN, then you must qualify the column name in the SELECT clause. INTO clause The INTO clause of the SELECT statement names the COBOL host variables into which DB2 will place the results table data. SELECT FNAME, LNAME INTO :FIRST, :LAST The data from FNAME will be placed into the host variable FIRST and data from LNAME will be put into LAST . SELECT FNAME, LNAME FROM PERSON Embedded SQL -- Select
  272. 273. WHERE clause The WHERE clause is used to specify a selection condition that identifies what rows DB2 should retrieve. This clause is optional. Format of WHERE clause: WHERE expression1 operator expression2 Example: WHERE SALARY < :MAXSAL

×