Upload
oscar-lester-shepherd
View
409
Download
0
Embed Size (px)
Citation preview
DUT
单位:大连理工大学作者:陆坤,李凤岐,姜厚云
1
大型主机平台系统应用开发基础 教育部- IBM精品课程
DUT
2
第九章 嵌入式数据库编程基础
9.1 大型机数据库对象介绍9.2 嵌入式 SQL 编程基础9.3 程序准备9.4 游标的使用9.5 动态 SQL 基础9.6 数据库的权限和锁的机制
DUT
3
第一节大型主机数据库对象介绍
IBM 数据库历史主机数据库中的对象 ;创建存储组 , 数据库 , 表空间 , 表 , 试图 , 同
义词 , 别名索引等对象 ;数据在数据库中的存储方式;How to use SPUFI
DUT
IBM DB2 发展史 四十年的理论研究应用产品, IBM 公司在数据库管理系统的研究和发展
中作出了巨大的贡献。 70 年代之前,层次型数据库占主导地位 (IBM IMS); 1970 年 ,IBM 研究中心 E.F. Codd 博士提出了关系数据库模型 , 紧接着 IBM 研
究中心发明了第一个关系数据库管理系统 SYSTEM R 和 SQL 语言 . 80 年代,基于 SQL 的关系数据库逐渐成为驻留, IBM 的关系数据库 DB2 住
在了大型机上的数据库应用。 1992 年 IBM 将 DB2 推向开放平台; 1997 年 IBM 发布 DB2 UDBV5 ,市场急剧扩大; 1999 年 IBM 发布 DB2V6 ,占据市场领导地位; 2000 年 IBM 发布 DB2V7.1— 电子商务数据库; 2001 年 IBM 发布 DB2V7.2— 电子商务数据库增强版; 2002 年 IBM 发布 DB2V8.1— 智能数据库; 2007 年 IBM 发布 DB2V9 — 第一个混合型数据库;
DUT
IBM 引导信息管理走向新的高度
DUTIBM 在关系数据库技术领域的领导地位
DUT
DB2 的先进性和广泛性 近 40 年关系数据库经验 超过 260 项数据库专利技术 Fortune 100, 100% 使用 DB2 Fortune 500,80% 使用 DB2 超过 1,000,000 张使用许可证 超过 60,000,000 最终用户 超过 450,000 公司使用 DB2 全世界 70 %的企业数据存储在 DB2 中
DUT
DB2: 增长最快的数据库
DUT
DB2- 平台延伸最好的数据库 (1/3)
DUT
DB2- 平台延伸最好的数据库 (2/3)
DUT
DB2- 平台延伸最好的数据库 (3/3)
DUT
DB2 Objects
DB2 Objects
DUT
Sequence of defining objects
DUT
Interfaces to define object
SQL Interfaces - Command line or file input interfaces
- SPUFI – SQL Processor Using File Input.( 重点) Tool on z/OS for entering SQL via file input
- QMF – Query Management Facility.
z/OS or workstation tool to allow interactive
SQL entry and processing.
- CLP – Command Line Processor.
It is used to dynamically execute SQL requests and/or DB2 commands.
DUT
DB2 Naming Rules (1/2)
DUT
DB2 Naming Rules(2/2)
DB and STG name must be unique in DB2 System All object names begin with A-Z,#,$;
following chars: A-Z,#,$,0-9; Name length: DB,TBS <= 8
others: <=128
DUT
DB2 Storage Group
DUT
Volumes
Are used in order Not dedicated to STG
Non-DB2 DS can be allocated on it One Can be assigned to different STG
MAX 133 volumes in a STG All volumes in a STG must the same type
DUT
DB2 Database
DUT
DB2 Database
CREATE DATABASE DB1
STOGROUP SG1 default STGBUFFERPOOL BP1 dflt table bp
INDEXBP BP2 dflt index bpCCSID UNICODE; dflt code
DSNDB04 is the default DB and is created when DB2 is installed.
DUT
DB2 Table Space
What is a Table Space?DB2 storage StructureContains data rows for one or more tablesResides in a page set of one or more VSAM LDSCreated in a database using SQL
Three types of Table space:Simple Table SpaceSegmented Table SpacePartitioned Table Space
DUT
Simple Table Space
Seldom used!
DUT
Segmented Table Space
DUT
SMPL and SEGMT Table Space
DUT
Partitioned(Table-Controlled) Table Space
DUTTable-Controlled Partitioning Example(1/2)
DUT
Table-Controlled Partitioning Example(2/2)
DUT
Create Table-column attribute
DATABASE
TABLESPACE
DUT
Default Attribute(1/2)
DUT
Default Attribute(2/2)
DATA TYPE SYSTE DEFAULT
-------------------------------------------CHARACTER SPACES
NUMERIC 0s
VARCHAR ZERO LENGHTH
DATE CURRENT DATA
TIME CURRENT TIME
TIMESTAMP CURRENT TIMESTAMP
DUT
CREATE TABLE- LIKE
•CHECK CONSTRAINS ARE NOT COPYED
•PR ,UNIQ,FK ARE NOT COPYED
DUT
SYSTABLES Catalog Information
DUT
Table Check Constraint Consideration
DUT
-DISPLAY DATABASE Command
-DIS DB (DSNDB06)
,CHKP
DUT
DB2 SYNONYM
Refer to a local table or view Refer to another owner’s tab or view as if it were yours. It can be thought of as a ‘private’ pointer to a table or view. A synonym can only be referenced by its owner
DUT
DB2 SYNONYM - Example
DUT
DB2 ALIAS
It is a pointer to a table or view It likes a virtual table It can be referenced by using a qualified name. The table or view could be located on a remote site.
DUT
DB2 ALIAS - Example
DUT
Naming Conversation for DS
DUTHow to use SPUFI ( SQL Processing Using File Input)
Environment Mainframe IP Address: 如: 218.25.163.36 DB2 subsystem: DB8G TSO USERID
• Each student has his own TSO Logon USERID. Use the USERID you are assigned to logon.
User datasets used in the practice – ST***.SPFUI.INPUT(SQL1)– ST***.SPFUI.OUTPUT
Note:
(1) These datasets are pre-created for each USER.
(2) Later we will see that these two datasets are used as SPUFI input and SPUFI output. And each user should use his own datasets. So when you take your practice, change *** to your USERID suffix.
DUT
How to use SPFUI
Practice Steps (1) Connect to z/OS(2) Invoke DB2 panel(3) Set SSID parameter that tell SPUFI which DB2 subsystem
you’ll operate on. (4) Use SPUFI to manage DB2 data
• Set SPUFI Parameters • Define SQL input file to SPUFI• Define SQL output file to SPUFI• Enter edit panel and edit your queries ( you can have DDL, DML,DCL
here) • Run test queries through SPFUI and view results
(5) Use SPUFI to run your own queries(6) Summary
DUT
How to use SPFUI
Invoke DB2 panel After you have enter ISPF. Type m.11.1 and type “enter key”, you will go to
DB2 panel.
DUT
How to use SPFUI
Set target DB2 subsystem to SPUFI Picture shows the DB2 panel, choose “D”, the panel to set db2
subsystem will appear.
Current set DB2 subsystem that SPUFI will operate on
Form here, you can go to the panel which set DB2 subsystem that SPUFI will operate on
DUT
How to use SPFUI
Set target DB2 subsystem to SPUFI (Continue) The picture below show how you set target DB2 subsystem. In our
testing environment it’s DB8G. Type DB8G and enter.
Type DB8G here to set the target DB2 subsystem as DB8G
DUT
How to use SPUFI
Invoke SPUFI
Target DB2 subsystem: DB8G
Enter 1 to invoke SPUFI
DUT
How to use SPUFI
Input/output datasets SPUFI uses datasets to hold it’s input/output. Before use, you must first
created these two datasets. In practice, please use “ST***.SPUFI.INPUT(SQL1)” and “ST***.SPUFI.OUT” which have been created
Input Dataset containing the SQL
Where the destination output will go
DUT
Edit SQL You can edit the query from edit panel just like editing a normal
datasets. And you can also save all your changes
Run SQL • Edit panel F3Ctrl
How to use SPUFI
DUT
View results After you run SPUFI, result page will appear as below picture Enter “F3” to go back to edit panel
How to use SPUFI
DUT
Run your own queries Run your own DDL
• Sample: Create table test(c1 int, c2 int);
Run your own DML • Sample: insert into test values(1, 1);
• Sample: select * from test;
Run your own DCL • Grant select on test to public;
Summary
How to use SPUFI
DUT
52
第二节 嵌入式编程基础
Using DelimitersUse Host variablesUse appropriate techniques to process
null dataSQLCA
DUT
Delimiters(1/2)
Used by PRECOMPILER to identify SQL stmt to be translated
Must indicate beginning and end of each embedded SQL stmt
COBOL EXEC SQL SQL STMT END-EXEC.
C;C++;PL/1
EXEC SQL SQL STMT ;
Java #sql{ SQL STMT };
FORTRAN EXEC SQL SQL STMT
DUT
SQL STMT in COBOL PROGRAMEXEC SQL
UPDATE TEMPL
SET WORKDEPT = ‘C02’ WHERE WORKDEPT = ‘C01’
END EXEC.
Notice: All COBOL delimiters and SQL statements must
begin at or after column 12.
SQL STMT in C or PL/I program EXEC SQL
UPDATE TEMPL
SET WORKDEPT = ‘C02’ WHERE WORKDEPT = ‘C01’ ;
In Java#sql { UPDATE TEMPL
SET WORKDEPT = ‘C02’ WHERE WORKDEPT = ‘C01’} ;
Delimiters(1/2)
DUT
Host Variables
Host Variable is used to allow
setting a value before statement
is executed.
Host variable in SQL statement
preceded by a colon
Host variable must match column data type
Not usable for DB2 names ( Table name, column name,…)
NOTE: You can use any valid COBOL name for a host variable. Do not use host variable names that begin with ‘SQL’.
宿主变量是在程序和 DB2 之间传递数据的手段。
DUTHost Variables- insert a single row
SQL statement
INSERT INTO TEMPL (EMPNO, LASTNAME)
VALUES (‘000190’, ‘JONES’)
SQL statement in a program
EXEC SQL
INSERT INTO TEMPL (EMPNO, LASTNAME)
VALUES (:EMPNO, :NAME)
END-EXEC.
DUT
SQL statement
UPDATE TEMPL
SET SALARY = SALARY * 1.05
WHERE JOBCODE = 54
SQL statement in a program
EXEC SQL
UPDATE TEMPL
SET SALARY = SALARY * :PERCENT
WHERE JOBCODE = :CODE
END-EXEC.
Host Variables - Update
DUT
EXEC SQLSELECT LASTNAME, WORKDEPT
INTO :NAME, :DEPTNODEPTNOFROM TEMPLWHERE EMPNO = :EMPID
END-EXEC.
● Each column selected must have a corresponding host variable● The host variables are separated with commas.
Host Variables – To Receive a single row
DUTHost Variables - Specifying expressions in the SELECT
When you specify a list of items in the SELECT clause, you can use more than the column names of tables and views. You can request a set of column values mixed with host variable values and constants
Example 1MOVE 4476 TO RAISE.
MOVE ’000220’ TO PERSON.
EXEC SQL
SELECT WHERE EMPNO = :PERSON END-EXEC.
EMPNO, LASTNAME, SALARY, :RAISE, SALARY + :RAISE
INTO :EMP-NUM, :PERSON-NAME, :EMP-SAL, :EMP-RAISE, :EMP-TTL
FROM DSN8810.EMP
Example 2MOVE ’D11’ TO DEPTID.
EXEC SQL SELECT WORKDEPT, AVG(SALARY) INTO :WORK-DEPT, :AVG-SALARY FROM DSN8810.EMP
WHERE WORKDEPT = :DEPTID END-EXEC.
59
DUT
Declaring Host Variables
DUT
SQL type mapped to COBOL declarations(1/2)
DUTSQL type mapped to COBOL declarations(2/2)
DUT
Declaration Considerations For COBOL
CREATE TABLE SIMPLE (TITLE CHAR(20) NOT NULL
NUMBER SMALLINT NOT NULL)
DATA DIVISION.
WORKING-STORAGE SECTION.EXEC SQL BEGAIN DECLARE SECTION END-EXEC.
01 IOAREA. 02 TITLE PIC X(20) 02 NUMBER S9(4) COMP.
EXEC SQL END DECLARE SECTION END-EXEC. PROCEDURE DIVISION.
EXEC SQLSELECT TITILE INTO:IOAREA.NUMBERFROM SIMPLE
WHERE NUMBER = :IOAREA.NUMBER
END-EXEC.
DUTDCLGEN-(Declarations Generator)
DUTDCLGEN-(Declarations DCLGEN-(Declarations
Generator)Generator)
DUT
DCLGEN - example(1/2)
DUT
DCLGEN - example(2/2)
DUT
COBOL 程序中的 SQL INCLUDE 语句用于包含 DCLGEN声明。这样程序开发者就不用手工将 DCLGEN 自动生成的数据表或视图所对应的宿主变量结构写入 COBOL 源代码,而只需要将如下简单的语句写入 COBOL 源代码:
EXEC SQL
INCLUDE DEPT
END-EXEC.
68
DCLGEN
DUT
Host Structure Support in COBOL
DUT
Host Structure Support in COBOL
DUT
Processing Null Data
DUT
Indicator Variables
INDICATOR VARIABLE(SMALLINT) is required if SELECTedcolumn allows null.
If column is NULL, INDICATOR VARIABLE is set to negative value (usually -1), VALUE VARIABLE is untouched. If column is NOT NULL, INDICATOR VARIABLE is set to positive value (usually 0).
INDICATOR VARIABLE can be set to negative value by program to indicate NULL on UPDATE or INSERT.
DUT
Indicator Variable Example
主机变量和 indicator variable 之间没有分号
DUT
Testing or Passing Null value
Tesing for NULL on SeletctEXEC SQL
SELECT JOBCODE,WORKDEPT,PHONENO
INTO:JC :JCI,:DPT,:PHO:PHOI
FROM TEMPL
WHERE EMPNO=:ID
END-EXEC.
IF JCI<0 MOVE “UNKN’ TO JC.
Passing NULL ValueIF(some condition) MOVE -1 TO PHOI
ELSE MOVE 0 TO PHOI.
EXEC SQL
UPDATE TEMPL
SET PHONENO=:PHONENO:PHI
WHERE EMPNO=:ID
END-EXEC.
DUT
Indicator Variable Usage – Null Value
DUT
SQLCA - SQL Communication Area
SQLCA : SQL 通信区,在每个 SQL 语句或 DB2 命令执行的最后更新, DBA 使用 SQLCA 结构可将 SQL 语句执行的结果信息返回给应用程序。
DUT
SQLCA 结构
01 SQLCA.05 SQLCAID PIC X(8).05 SQLCABC PIC S9(9) COMP.05 SQLCODE PIC S9(9) COMP.05 SQLERRM.
49 SQLERRML PIC S9(4) COMP.49 SQLERRMC PIC X(70).
05 SQLERRP PIC X(8)05 SQLERRD OCCURS 6 TIMES
PIC S9(9) COMP.05 SQLWARN
10 SQLWARN0 PIC X(1).10 SQLWARN1 PIC X(1).10 SQLWARN2 PIC X(1).……10 SQLWARN7 PIC X(1).
05 SQLEXT.10 SQLWARN8 PIC X(1).10 SQLWARN9 PIC X(1).10 SQLWARNA PIC X(1).10 SQLSTATE PIC X(5).
DUT
SQLCA Codes
DUT
Some Common SQLCODE Values
DUT
SQLCA Warnings
DUT
Coding Aids
DUT
Coding Aids
WHENEVER Statement
- For exception handling Error message formatting routine
- CALL ‘DSNTIAR’ for COBOL on z/OS
- CALL DSNTIAR for PL/I on z/OS INCLUDE statement and INCLUDE files
- To add SQLCA structures to program and to provide function prototypes
DUT
WHENEVER Statement
WHENEVER 语句:出错捕获语句,根据 SQL 语句返回的SQLCODE 决定是继续执行还是转向出错处理例程。其格式为:EXEC SQL WHENEVER Condition Action;
DUT
WHENEVER Statement
Condition:- SQLERROR
● Negative SQLCODE- SQLWARNING
● Positive SQLCODE (not +100) ● Or SQLWARN0=‘W’
- NOT FOUND ● SQLCODE=+100
Action:- GO TO :X
● Control transferred to statement labeled X- CONTINUE
● Program continues with next statement ● Used to cancel effect of prior WHENEVER
DUT
WHENEVER Statement Example
EXEC SQL WHENEVER NOTFOUND
GOTO :PROG-END.
……
EXEC SQL
SELECT COL1 FROM TB1 WHERE
COL2=‘C1’
END-EXEC.……
PROG-END.
EXIT.
DUT
Error Message Formatting Routine
In z/OS, there is an Error Message Formatting Routine - DSNTIAR.
Format: CALL ‘DSNTIAR’ USING sqlca message lrecl
DSNTIAR takes error message from the SQLCA, formats it into a more readable form, and places the result in a message output area that you provide in your application program.
DUTAlternative to WHENEVER - COBOL Program
/*DECLARES FOR DSNTIAR*/01 ERROR-MESSAGE.
02 MESSAGE-LENGTH PIC S9(4) COMP VALUE +960.02 DETAIL-MESSAGE PIC X(120) OCCURS 8 TIMES.
01 LINE-LENGTH PIC S9(9) COMP VALUE +120.
SQL StatementIF SQLCODE < 0
CALL ‘DSNTIAR’ USING SQLCA ERROR-MESSAGE LINE-LENGTH.IF RETURN-CODE < 5
MOVE DETAIL-MESSAGE(1) TO DISPLAY-MESSAGE.MOVE DETAIL-MESSAGE(2) TO DISPLAY-MESSAGE.MOVE DETAIL-MESSAGE(3) TO DISPLAY-MESSAGE.
……
DUT
SQL INCLUDE Statement
DUT
89
第三节 程序准备
Understand the whole process to Understand the whole process to program a DB2 applicationprogram a DB2 application
Understand package and planUnderstand package and planUnderstand rebind strategyUnderstand rebind strategy
DUT
Programming process
DUT
Programming process
Compile/Link-edit
DUT
Programming process
在嵌入式的 SQL 编程中,源程序包含应用代码和 SQL 语句。
程序在相关的源代码语言编译器编译之前,嵌入的 EXEC SQL 语句必须首先替换掉,替换成源代码的一些 CALL 调用语句。
这种用程序库调用来替换 SQL 语句的过程,由 DB2 的一个进程来完成,称为预编译器。
对于静态的嵌入式 SQL 程序, SQL 语句会由 DB2 的 bind过程来进行处理,生成 package
DUT
Programming process
Normally a DB2 application has to go through 4 steps to complete an execution: Precompile Compile/Link-edit Bind Run (Execution)
During the process, below source are accessed or generated: Source code modules with embedded SQL Source code modules with DB2 APIs DBRM(bind files) Collection and Package Plan
DUT
Precompile
94
DUT
Precompile
Precompile
DB2 precompiler takes the application source code as input, and generates two outputs: modified code and DBRM
Precompiler comments out the SQL statements in the source code and replace them by language-specific calls.
From all the SQL statements it encounters, the precompiler constructs a DBRM, which then becomes the input of the Bind component.
DUT
Precompile
Precompile
预编译器在处理的时候,并不访问 DB2
预编译器会验证 SQL 语法,还会为每个 SQL 产生一个一致性令牌和语句号。
预编译器会将 EXEC SQL INCLUDE 语句要引入的文件都 included进来。
DUT
DBRM
DBRM
- One DBRM corresponds to exactly one source module
- contains extracted, parsed SQL source;
- Is stored as a member in a partitioned dataset;
- one member or file created per precompile;
- will become input to BIND.
DUT
Compile/Link-edit
98
DUT
Compile/Link-edit
Compile/Link-edit
After compilation, the modified source code is compiled using the corresponding language-specific compiler into object module
The generated object module is linked with other (possible) object module to generate a load module for the whole application.
DUT
Compile/Link-edit
DUT
Bind
DUT
Bind
DUT
BIND
Bind package “Bind” a given DBRM to produce a package
When the bind file or DBRM is bound to the database, a package is created in the database. This package contains instructions about how to execute the SQL statements that were included in the source code.
A DBRM can be thought of as a “SQL source module”,while the package can be thought of the corresponding “object module”.
Bind Plan : “Bind together” a list of packages(and/or a list of DBRMs) to produce
a plan.
DUT
BIND
DUT
BIND
Validation checks on the existence of necessary DB2 objects, for example, tables, views, and so forth.
With the resolution of table names, DB2 implicitly appends an unqualified table name with its owner’s ID.
Authority checking is performed to make sure that the BINDer or owner has the authority to create a program to access the data as required.
Access path selection consists of evaluating a number of different access paths and calculating their costs. The cheapest one will be retained.
The executable access code is stored in the directory, and the source SQL statements are stored in the DB2 catalog.
105
DUT
RUN
DUT
Bind- package and plan
107
DUT
Bind process
DUT
Bind process
DUT
Bind
- BIND PACKAGE(collection-id) MEMBER(dbrm-member).
110
DUT
Collection ID
Package are qualified with a collection. Package Name = Collection_Id.Package_Id
DUT
Plans
DUT
Package List A package list is a list of reference to individual packages
DUT
Package and Plan
In between the load module and the packages, there is a need for an additional structure that will "guide" DB2 in its search for the appropriate package. This structure is called a "PLAN",
A PLAN contains a “PACKAGE LIST”, a list of pointers to packages
A package can only be located and executed via a PLAN
The dbrm name and the timestamp provided with the call is used to LOCATE the correct package via the package list
DUT
Overview with packages
DUT
116
第四节 游标的使用 Use DECLARE, OPEN, FETCH, and CLOSE Use DECLARE, OPEN, FETCH, and CLOSE
CURSOR statements to handles select CURSOR statements to handles select criteria that may return multiple rows in criteria that may return multiple rows in application programs.application programs.
Issue positioned UPDATE and DELETE Issue positioned UPDATE and DELETE statements (Know how to update and delete statements (Know how to update and delete rows with a cursor)rows with a cursor)
Multi-Row Fetch Host Variable Arrays
DUT
Processing Result Set
仅返回一行的 SELECT 语句的结果的处理? 通过 INTO 将结果放到宿主变量
多行呢? 按上述方法:第一行放置在 INTO 字句定义地宿主变量中,同时
SQLCODE 被置为- 811
DUT
Processing Multiple Rows
DUT
Sequential File Read
DUT
Sequential File Read
1.Define file access
2.Open the file for reading
3.Read the first record
4.Read the next record
5.close the file
DUT
Select with FETCH - COBOL
DUT
CURSOR
DECLARE: 定义游标;游标名称和这个游标对应的 SQL 语句。DECLARE 语句不执行 SQL 语句,仅定义。
OPEN :为检索列而准备好游标;打开游标,则执行相应的 SQL ,建立结果表。
FETCH: 从结果表中取数据,一次一行,并且给指定的宿主变量赋值。(一直 loop 到 SQLCODE=100 )
CLOSE :释放游标使用的所有资源。
DUT
Select with FETCH - C or PL/I
DUT
DELETE Via a Cursor - COBOL
DUT
UPDATE Via a Cursor - COBOL
DUT
U – Lock Usage
DUT
Without FOR UPDATE OF
Terminal 1 issues the open cursor and fetches the first row. Receives an IS lock on the table, an S lock on the row.
Terminal 2 issues the open cursor and fetches the first row. Receives an IS lock on the table, an S lock on the row.
Terminal 1 tries to update the row it is reading. It gets an IX lock on the table through lock conversion. It needs to get an X lock on the row. It cannot get an X lock on the row since terminal 2 holds an S lock on the row. So, terminal 1 waits.
Terminal 2 decides to update the row it is reading. It gets an IX lock on the table through lock conversion. It needs to get an X lock on the row. It cannot get an X lock on the row since terminal 1 holds an S lock on the row. This is a 'deadlock'.
DUT
With FOR UPDATE OF
Terminal 1 issues the open cursor and fetches the first row. Receives an IX lock on the table, an U-lock on the row.
Terminal 2 issues the open cursor and fetches the first row. Receives an IX lock on the table, but waits for a U-lock on the row.
Terminal 1 updates the row it is reading. It upgrades its lock to an X lock on the row.
Terminal 2 will wait until terminal 1 commits or it times out. Getting the U-locks may limit concurrency, but in this case, it prevented a deadlock.
DUT
Update/Delete Via a Cursor
DUT
Optimizer for n ROWs
DUT
Fetch first k Rows only
DUT
Cursor Manipulation
DUT
Cursor Manipulation
CLOSE CURSOR releases the cursor, and addressability to the buffer is lost.
If a cursor is to be reused, it must be CLOSED before it is OPENED.
COMMIT will CLOSE any CURSOR that has not been defined WITH HOLD. (See the next visual.)
DUT
WITH HOLD Cursor
即使 commit, 游标仍持有
DUT
Cursor Repositioning
REQUIRMENT: UPDATE of a large number of rows, using a CURSOR. To avoid accumulating an excessive number of ROW LOCKS, issue a COMMIT after every 500 UPDATES.
CONSIDER: If restart capabilities must be included in the program, position of the cursor must be reestablished.
SULUTION: After ABEND , reestablish position based upon a saved column value.
DUT
Cursor repositioning – COBOL (1/2)
DUT
Cursor repositioning – COBOL (2/2)
DUT
Scrollable Cursors
DUT
Scrollable Cursors
静态游标和动态游标的区别:
静态游标打开后,结果集的大小不变,结果集中行的数据顺序也不变。
动态游标打开后,结果集的大小可变,结果集中行的数据顺序也可变,即其他游标可以对结果集中进行插入,更新或删除操作。
DUTWhat Happens When a Scrollable Cursor is Opened?
DUT
How to Scroll within the Result Table
DUT
How to Scroll within the Result Table
The RELATIVE keyword is used to position the cursor relative to the current position.
ABSOLUTE keyword is used to position the cursor relative to the top or bottom of the result table
FETCH PRIOR, FETCH NEXT,FETCH FIRST, FETCH LAST
An example of the full syntax is as follows:
FETCH SENSITIVE RELATIVE 3 FROM C1 INTO :hv1, :hv2
DUT
Scrollable Cursors
DUT
How to Declare a Scrollable Cursor
DUT
Insensitive Scrollable Cursors
DUT
Sensitive Scrollable Cursors
DUT
Sensitive and Insensitive
敏感和不敏感游标的区别:
不敏感的游标意味着在游标打开后,不能看到其他应用对基础表中的更改( 包括数据插入,更新和删除) ,不敏感的游标是只读的,结果表中行的数量和内容在游标打开的整个过程中不变。不敏感的游标不能用于数据更新和删除。
敏感的游标意味着在游标打开后,能够看到其他应用对基础表所作的更改,结果表中行的数量( 其他应用插入或删除) 在游标打开的整个过程中不变,但是行的内容可变 。敏感的游标能够用于数据更新和删除。
DUTFetch sensitive request which creates an Update Hole
DUTWhat happens when a FETCH request encounters a Hole in the Result Table?
DUTDynamic Scrollable Cursors – New in V8
DUT
New in V8 -Dynamic Scrollable Cursors
Dynamic scrollable cursor allow for base table access instead of having to use a declared global temporary table .
Each FETCH shows the most current activity and is sensitive to all INSERTs,UPDATEs, and DELETEs:no more delete holes and missing updates-- allows visibility of updates and inserts done by you or other users
DECLARE DyCur SENSITIVE DYNAMIC SCROLL CURSOR FOR
SELECT TCID,NAME FROM TEST_CENTER;
DECLARE DyCur SENSITIVE DYNAMIC SCROLL CURSOR FOR
SELECT TCID,NAME FROM TEST_CENTER;
DUT
Cursors Type comparision
DUT
各游标定义和取数据时各不同参数的区别总结
DECLARE CURSOR 时使用的参数
FETCH 时使用的参数
注释 对基础表更改的敏感性
INSENSITIVE INSENSITIVE FETCH 缺省值是INSENSITIVE
无
INSENSITIVE SENSITIVE 无效组合 ---
SENSITIVE INSENSITIVE 有效组合 应用能看到自身采用 positioned 更新和删除所作的改变
SENSITIVE SENSITIVE FETCH 缺省值是SENSITIVE
应用能看到 :1. 自身采用positioned 和searched 更新和删除所作的改变2. 其他应用提交的更新和删除
DUTHow to choose the right Type of Cursor
DUT
Multiple Row Processing
DUT
Multi-Row FETCH
What is it?
- Multi-row FETCH: A single FETCH statement can retrieve multiple rows of data from the
result table of a query as a rowset A rowset is a group of rows of data that are grouped together and
operated on as a set
Benefits
- Enhances usability and power of SQL
- Performance is improved by eliminating multiple trips between application and database engine; for distributed access, reduced network traffic
DUT
DECLARE CURSOR Example
Declare C1 as the cursor of a query to retrieve a rowset from table EMP
EXEC SQL
DECLARE C1 CURSOR
WITH ROWSET POSITONING
FOR SELECT * FROM EMP;
WITH ROWSET POSITIONING specifies whether multiple rows of data can be accessed as a rowset on a single FETCH statement.
NOTE: Do not specify the size of the rowset (FOR n ROWS) on the DECLARE CURSOR statement. That is done at FETCH time.
(FOR n ROWS clause of the FETCH statement controls how many rows are returned on each FETCH statement.)
DUT
FETCH Examples
EXAMPLE 1:
Fetch the previous rowset and have the cursor positioned on that rowset
EXEC SQL
FETCH PRIOR ROWSET FROM C1 FOR 3 ROWS INTO……
or
EXEC SQL
FETCH ROWSET
STARTING AT RELATIVE -3 FROM C1 FOR 3 ROWS INTO……
DUT
FETCH Examples
EXAMPLE 2:
Fetch 3 rows starting with row 20 regardless of the current position of the cursor
EXEC SQL
FETCH ROWSET STARTING AT ABSOLUTE 20
FROM C1 FOR 3 ROWS INTO……
DUT
Host Variable Arrays
● A host variable array is an array in which each element of the array contains a value for the same column
● Can only be referenced in multi-row FETCH and INSERT
● Host variable arrays are supported in:
- COBOL
- PL/I
- C and C++
DUT
COBOL Example
Declare cursor C1 and fetch 10 rows using a multi-row FETCH statement01 OUTPUT-VARS.
05 NAME OCCURS 10 TIMES.49 NAME-LEN PIC S9(4) USAGE COMP.49 NAME-TEXT PIC X(40).
05 SERIAL-NUMBER PIC S9(9) USAGE COMP OCCURS 10 TIMES.01 IND-VARS.
10 INDSTRUC1 PIC S9(4) USAGE COMP OCCURS 10 TIMES.10 INDSTRUC2 PIC S9(4) USAGE COMP OCCURS 10 TIMES.
PROCEDURE DIVISION.EXEC SQL
DECLARE C1 SCROLL CURSOR WITH ROWSET POSITIONING FORSELECT NAME, SERIAL FROM EMPLOYEE
END-EXEC.EXEC SQL OPEN C1 END-EXEC.EXEC SQL
FETCH FIRST ROWSET FROM C1 FOR 10 ROWSINTO :NAME:INDSTRUC1, :SERIAL-NUMBER:INDSTRUC2
END-EXEC.
DUTUsing Multi-Row FETCH with Scrollable Cursors
● As holes may occur, ensure at least one indicator variable array is defined for a column
- Even if no nullable columns exist add an indicator variable array for at least one column
- If nullable columns exist all indicator variable arrays provided are updated if a hole is found
● Value of -3 indicates hole
● SQLCODE +222 is also returned
DUTCursor Positioning: Rowset Positioned Fetches
DUT
Mixing Row and Rowset Positioning
DUT
Partial Rowsets (Result Sets)
DUT
168
第五节 动态 SQL 基础 Difference between static and dynamic SQL;Difference between static and dynamic SQL;
List the type of dynamic statementsList the type of dynamic statements
Code dynamic SQL in programCode dynamic SQL in program
DUT
Static and Dynamic
仅返回一行的 SELECT 语句的结果的处理? 通过 INTO 将结果放到宿主变量
多行呢? 第一行放置在 INTO 字句定义地宿主变量中,同时 SQLCODE 被
置为- 811
DUT
Static and Dynamic
DUT
Static Versus Dynamic
DUT
Type of Dynamic SQL statements
DUTComplete Non-SELECT Statement
DUTComplete Non-SELECT Statement
最简单的 一旦获取语句,则 PREPARE,EXECUTE. PREPARE:即创建 ACCESS PATH. EXECUTE IMMEDIATE 会立即执行这两个功能。
DUTComplete Non-SELECT Statement
DUT
Parameterized Non-SELECT statement
DUT
Parameterized Non-SELECT statement
DUT
PREPARE 语句使得 STMT 的内容,被动态 BIND. 成功,则结果可以被后面以 PRST 为名来引用之
每个 PREPARED 语句,都有一个唯一的名字,且被CACHE, 一直到这个应用中有同名语句的 PREPARE
位置参数值在 EXECUTE 的时候提供。
DUT
SELECT statement with Fixed List
DUT
SELECT statement with Varying List
DUT动态 SQL 语句概念
嵌入式动态 SQL 将获取数据的命令 ( 不是数据本身,这一点与静态SQL 不同 ) 存入宿主变量中,这些语句将由 PREPARE 语句在运行时进行预编译。
动态 SQL 需要增加 PREPARE 和 EXECUTE 语句,以便在程序运行期间创建存取路径和执行 SQL 语句。
使用动态 SQL 的样例如下: EXEC SQL DECLARE C1 CURSOR FOR S1 END-EXEC. EXEC SQL PREPARE S1 FROM :var0 END-EXEC. EXEC SQL EXECUTE S1 USING :var1,:var2 END-EXEC. EXEC SQL OPEN C1 END-EXEC. PERFORM ... UNTIL SQLCODE = +100 OR SQLCODE < 0. EXEC SQL FETCH C1 INTO ... END-EXEC. DISPLAY ... EXEC SQL CLOSE C1 END-EXEC. 其中 C1 是 CURSOR 的名字, var0 中存放动态 SQL 语句的主干部分, var1 和 var2 中存放 SQL 语句需要的参数,可选。
DUT
静态 SQL 语句与动态 SQL 语句的区别 在实际情况中,绑定包,计划和执行计划可能不是同一用
户。 1. 对于静态 SQL 语句来说,绑定包和计划的用户既需要对
应的 BIND 权限,又需要具体 SQL 语句的权限,而执行计划的用户只需要 EXECUTE 权限;
对于动态 SQL 语句来说,绑定包和计划的用户只需要对应的 BIND 权限,而执行计划的用户既需要 EXECUTE权限,又需要具体 SQL 语句的权限。
2. 静态 SQL适用于在绑定包和计划与执行计划时间间隔内表数据不频繁更新 ( 包括插入,更新和删除 ) 的情况,而动态 SQL适用于该时间间隔内表数据更新频繁的情况。
DUT
183
www.themegallery.com