The FETCH statement positions a cursor on the next row of its result table and assigns the values of that row to target variables.

Invocation

Although an interactive SQL facility might provide an interface that gives the appearance of interactive execution, this statement can only be embedded within an application program. It is an executable statement that cannot be dynamically prepared. When invoked using the command line processor, the syntax following cursor-name is optional and different from the SQL syntax.

For more information, refer to Using command line SQL statements and XQuery statements .

Authorization

For each global variable used as a cursor-variable-name or in the expression for an array-index, the privileges held by the authorization ID of the statement must include one of the following:

  • READ privilege on the global variable that is not defined in a module
  • EXECUTE privilege on the module of the global variable that is defined in a module
For each global variable used as an assignment-target, the privileges held by the authorization ID of the statement must include one of the following:

  • WRITE privilege on the global variable that is not defined in a module
  • EXECUTE privilege on the module of the global variable that is defined in a module

For the authorization required to use a cursor, see "DECLARE CURSOR".

Syntax


>>-FETCH--+------+--+-cursor-name----------+-------------------->
    '-FROM-' '-cursor-variable-name-'        .-,---------------------.    
    V |    
>--+-INTO----| assignment-target |-+---+-----------------------><
   '-USING DESCRIPTOR--descriptor-name-'   


assignment-target >>-+-global-variable-name-------------------+------------------><
   +-host-variable-name---------------------+   
   +-SQL-parameter-name---------------------+   
   +-SQL-variable-name----------------------+   
   +-transition-variable-name---------------+   
   +-array-variable-name--[--array-index--]-+   
   '-field-reference------------------------'   

Description

cursor-variable-name
Identifies the cursor to be used in the fetch operation. The cursor-variable-name must identify a cursor variable that is in scope. When the FETCH statement is executed, the underlying cursor of the cursor-variable-name must be in the open state. A FETCH statement using a cursor-variable-name can only be used within a compound SQL (compiled) statement.
INTO assignment-target

Identifies one or more targets for the assignment of output values. The first value in the result row is assigned to the first target in the list, the second value to the second target, and so on. Each assignment to an assignment-target is made in sequence through the list. If an error occurs on any assignment, the value is not assigned to the target, and no more values are assigned to targets. Any values that have already been assigned to targets remain assigned.

When the data type of every assignment-target is not a row type, then the value 'W' is assigned to the SQLWARN3 field of the SQLCA if the number of assignment-targets is less than the number of result column values.

If the data type of an assignment-target is a row type, then there must be exactly one assignment-target specified (SQLSTATE 428HR), the number of columns must match the number of fields in the row type, and the data types of the columns of the fetched row must be assignable to the corresponding fields of the row type (SQLSTATE 42821).

If the data type of an assignment-target is an array element, then there must be exactly one assignment-target specified.

global-variable-name
Identifies the global variable that is the assignment target.
host-variable-name
Identifies the host variable that is the assignment target. For LOB output values, the target can be a regular host variable (if it is large enough), a LOB locator variable, or a LOB file reference variable.
SQL-parameter-name
Identifies the parameter that is the assignment target.
SQL-variable-name
Identifies the SQL variable that is the assignment target. SQL variables must be declared before they are used.
transition-variable-name
Identifies the column to be updated in the transition row. A transition-variable-name must identify a column in the subject table of a trigger, optionally qualified by a correlation name that identifies the new value.
array-variable-name
Identifies an SQL variable, SQL parameter, or global variable of an array type.
[array-index]
An expression that specifies which element in the array will be the target of the assignment. For an ordinary array, the array-index expression must be assignable to INTEGER (SQLSTATE 428H1) and cannot be the null value. Its value must be between 1 and the maximum cardinality defined for the array (SQLSTATE 2202E). For an associative array, the array-index expression must be assignable to the index data type of the associative array (SQLSTATE 428H1) and cannot be the null value.
field-reference
Identifies the field within a row type value that is the assignment target. The field-reference must be specified as a qualified field-name where the qualifier identifies the row value in which the field is defined.
USING DESCRIPTOR descriptor-name
Identifies an SQLDA that must contain a valid description of zero or more host variables.

Before the FETCH statement is processed, the user must set the following fields in the SQLDA:

  • SQLN to indicate the number of SQLVAR occurrences provided in the SQLDA.
  • SQLDABC to indicate the number of bytes of storage allocated for the SQLDA.
  • SQLD to indicate the number of variables used in the SQLDA when processing the statement.
  • SQLVAR occurrences to indicate the attributes of the variables.

The SQLDA must have enough storage to contain all SQLVAR occurrences. Therefore, the value in SQLDABC must be greater than or equal to 16 + SQLN*(N), where N is the length of an SQLVAR occurrence.

If LOB or structured type result columns need to be accommodated, there must be two SQLVAR entries for every select-list item (or column of the result table).

SQLD must be set to a value greater than or equal to zero and less than or equal to SQLN.

The nth variable described in the SQLDA corresponds to the nth column of the result table of the cursor. The data type of each variable must be compatible with its corresponding column.

Each assignment to a variable is made according to specific rules. If the number of variables is less than the number of values in the row, the SQLWARN3 field of the SQLDA is set to 'W'. Note that there is no warning if there are more variables than the number of result columns. If an assignment error occurs, the value is not assigned to the variable, and no more values are assigned to variables. Any values that have already been assigned to variables remain assigned.

Notes

  • Cursor position: An open cursor has three possible positions:

    • Before a row
    • On a row
    • After the last row.

    A cursor can only be on a row as a result of a FETCH statement. If the cursor is currently positioned on or after the last row of the result table:

    • SQLCODE is set to +100, and SQLSTATE is set to '02000'.
    • The cursor is positioned after the last row.
    • Values are not assigned to assignment targets.

    If the cursor is currently positioned before a row, it will be repositioned on that row, and values will be assigned to targets as specified by the INTO or USING clause.

    If the cursor is currently positioned on a row other than the last row, it will be repositioned on the next row and values of that row will be assigned to targets as specified by the INTO or USING clause.

    If a cursor is on a row, that row is called the current row of the cursor. A cursor referenced in an UPDATE or DELETE statement must be positioned on a row.

    It is possible for an error to occur that makes the state of the cursor unpredictable.

  • When retrieving into LOB locators in situations where it is not necessary to retain the locator across FETCH statements, it is good practice to issue a FREE LOCATOR statement before issuing the next FETCH statement, as locator resources are limited.
  • It is possible that a warning may not be returned on a FETCH. It is also possible that the returned warning applies to a previously fetched row. This occurs as a result of optimizations such as the use of system temporary tables or pushdown operators.
  • Statement caching affects the behavior of an EXECUTE IMMEDIATE statement.
  • DB2®CLI supports additional fetching capabilities. For instance, when a cursor's result table is read-only, the SQLFetchScroll() function can be used to position the cursor at any spot within that result table.
  • For an updatable cursor, a lock is obtained on a row when it is fetched.
  • If the cursor definition contains an SQL data change statement or invokes a routine that modifies SQL data, an error during the fetch operation does not cause the modified rows to be rolled back, even if the error results in the cursor being closed.

Examples

  • Example 1:  In this C example, the FETCH statement fetches the results of the SELECT statement into the program variablesdnum,dname, andmnum. When no more rows remain to be fetched, the not found condition is returned.

       EXEC SQL DECLARE C1 CURSOR FOR
    SELECT DEPTNO, DEPTNAME, MGRNO FROM TDEPT
    WHERE ADMRDEPT = 'A00'; EXEC SQL OPEN C1; while (SQLCODE==0) {
    EXEC SQL FETCH C1 INTO :dnum, :dname, :mnum;
    } EXEC SQL CLOSE C1;
  • Example 2:  This FETCH statement uses an SQLDA.
       FETCH CURS USING DESCRIPTOR :sqlda3

再来一发!DB2 应用程序如何从数据库取数据 Fetch的更多相关文章

  1. C#程序中从数据库取数据时需注意数据类型之间的对应,int16\int32\int64

    private void btn2_Click(object sender, RoutedEventArgs e)         {             using (SqlConnection ...

  2. 微信小程序云开发-数据库-删除数据

    一.js文件使用.remove()删除单条数据 在js文件中写updategood函数,在函数中使用.doc()指定要删除的数据id,调用.remove()方法删除数据. 二.wxml文件添加[删除] ...

  3. 微信小程序云开发-数据库-更新数据

    一.js文件代码使用.update更新数据 写一个更新数据的函数,函数内使用.update更新数据.一定要通过.doc指定修改哪一条数据.  二.wxml文件修改数据的按钮 在wxml文件中写[修改] ...

  4. python从数据库取数据后写入excel 使用pandas.ExcelWriter设置单元格格式

    用python从数据库中取到数据后,写入excel中做成自动报表,ExcelWrite默认的格式一般来说都比较丑,但workbook提供可以设置自定义格式,简单记录个demo,供初次使用者参考. 一. ...

  5. 从redis数据库取数据存放到本地mysql数据库

    redis数据库属于非关系型数据库,数据存放在内存堆栈中,效率比较高. 其存储数据是以json格式字符串存储字典的,而类似的关系型数据库无法实现这种数据的存储. 在爬取数据时,将数据暂存到redis中 ...

  6. 备忘录——C#获取微信小程序的云数据库中数据

    目录 0. 背景说明 0.2 获取AccessToken 0.3 数据库查询 0.4 文件下载 2. 简单的封装 3. 简单测试 4. 参考文档 shanzm-2021年8月17日 17:14:24 ...

  7. Jmeter—8 连接microsoft sql server数据库取数据

    本文以Jmeter 连接microsoft sql server为例. 1 从微软官网下载Microsoft SQL Server JDBC Driver 地址:http://www.microsof ...

  8. oracle 跨数据库取数据

    思路:先从另一个数据库里把数据取出来, 然后,把这个数据集合解析,根据这个数据集合拆分组合成一个创建oralce临时表的方法及数据的插入.紧接着就可以写sql语句进行联合查询了. 下面是具体实例的方法 ...

  9. 【转】最简单的CI框架入门示例--数据库取数据

    1.下载CI框架(自己找) 2.配置 database.php配置:    为数据库服务器设置 connection 参数: $db['default']['hostname'] = "yo ...

随机推荐

  1. FineUI第十六天---表格的排序和分页

    表格的排序和分页 1.表格的排序需要: AllowSorting:是否允许排序. SortColumn:当前排序的列ID,当然也可以不设置此属性,而是在后台初始化代码中直接指定默认排序字段. Sort ...

  2. Codeforces 260 B. Fedya and Maths

    题目链接:http://codeforces.com/contest/456/problem/B 解题报告:输入一个n,让你判断(1n + 2n + 3n + 4n) mod 5的结果是多少?注意n的 ...

  3. Unity手游之路<九>自动寻路Navmesh之高级主题

    http://blog.csdn.net/janeky/article/details/17492531 之前我们一起学习了如何使用Navmesh组件来实现最基本的角色自动寻路.今天我们再继续深入探索 ...

  4. cocos2d智能指针 转自:http://blog.csdn.net/nxshow/article/details/44699409

    智能指针在C++11的标准中已经存在了, 分别是unique_ptr,shared_ptr,weak_ptr, 其中最常用的应该是share_ptr, 它采用引用计数的方式管理内存, 当引用计数为0的 ...

  5. css 3d 动画 相关

    transform-style: preserve-3d; 设置3D模式 perspective:700px :属性定义 3D 元素距视图的距离,以像素计.该属性允许您改变 3D 元素查看 3D 元素 ...

  6. 【转】UML类图几种关系的总结

    在UML类图中,常见的有以下几种关系: 泛化(Generalization),  实现(Realization),关联(Association),聚合(Aggregation),组合(Composit ...

  7. 汉诺塔(河内塔)算法 ----C语言递归实现

    汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具.大梵天创造世界的时候做了三根金刚石柱子, 在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘.大梵天命令婆罗门把圆盘从下面开始按大小顺 ...

  8. bootstrap按钮组

    种类 -a,   input ,   button 块级 btn-block 按钮组 btn-group btn-group-justified btn-group-vertical </div ...

  9. Convert a given Binary Tree to Doubly Linked List

    The question and solution are from: http://www.geeksforgeeks.org/convert-given-binary-tree-doubly-li ...

  10. 时间和日期控件(Calendar1)

    取得选择的: taskItem["data"] = Calendar1.SelectedDate.ToShortDateString();