oracle游标fetch

SQL cursor is one of the most popular database objects. It is used to retrieve data from the result set of an SQL query one row at a time. Even if the cursor is not recommended from a performance perspective, they are still widely used especially when handling a small amount of data.

SQL游标是最流行的数据库对象之一。 它用于一次从一行SQL查询的结果集中检索数据。 即使从性能角度不建议使用游标,它们仍然被广泛使用,尤其是在处理少量数据时。

There are many related objects needed to use a cursor such as @@FETCH_STATUS function. In this article, we will try to describe SQL cursor briefly and then we will explain @@FETCH_STATUS function by providing some examples to clarify each of its returned values.

使用游标需要许多相关的对象,例如@@ FETCH_STATUS函数。 在本文中,我们将尝试简要描述SQL游标,然后通过提供一些示例来阐明@@ FETCH_STATUS函数,以阐明其返回值。

SQL游标概述 (SQL cursor overview)

As mentioned before, a cursor is a database object used to fetch the rows from a result set. There are different phases in a cursor life cycle:

如前所述,游标是用于从结果集中获取行的数据库对象。 游标生命周期有不同的阶段:

宣告游标 (Declaring cursor)

First of all, we need to create a cursor object. Mainly there are 2 required parameters:

首先,我们需要创建一个游标对象。 主要有2个必需参数:

  1. Cursor name 游标名称
  2. Source SQL query 源SQL查询

You must use the following syntax to declare a cursor object:

您必须使用以下语法声明游标对象:

DECLARE <Cursor_name> CURSOR FOR <Source_SQL_Query>

Note that source SQL query should be a SELECT statement, as for example, the following cursor is to read the table schemas and names created in a database:

请注意,源SQL查询应为SELECT语句,例如,以下游标用于读取在数据库中创建的表模式和名称:

DECLARE csrTables CURSOR FOR SELECT TABLE_SCHEMA, TABLE_NAME from INFORMATION_SCHEMA.TABLES

开启游标 (Opening cursor)

Declaring SQL cursor doesn’t mean that you can start reading data from the result set, first, you need to retrieve the source SQL query result which is done using the OPEN command. The command syntax is very simple, just write OPEN keyword plus the name of the cursor as follows:

声明SQL游标并不意味着您可以开始从结果集中读取数据,首先,您需要检索使用OPEN命令完成的源SQL查询结果。 该命令的语法非常简单,只需编写OPEN关键字以及游标的名称,如下所示:

OPEN <Cursor_name>

提取行 (Fetching rows)

After opening the cursor, the source SQL query is executed and the result set is stored in memory. The next step is to fetch rows and to visualize them or to store them within some declared variables. Note that each column in the result set must be mapped to a variable having a relevant data type.

打开游标后,将执行源SQL查询,并将结果集存储在内存中。 下一步是获取行并将其可视化,或将其存储在某些声明的变量中。 请注意,结果集中的每一列都必须映射到具有相关数据类型的变量。

The FETCH command syntax is as follows:

FETCH命令的语法如下:

FETCH NEXT FROM <cursor_name> [ INTO @variable_name [ ,...n ] ]

If you decide to only fetch rows without storing them within variables, the result will be displayed as a result of a select query:

如果您决定仅获取行而不将其存储在变量中,则结果将作为选择查询的结果显示:

Otherwise, if you choose to store the fetched rows within SQL variable you have to make sure that the order of the variables must be the same as the result set columns order:

否则,如果选择将获取的行存储在SQL变量中,则必须确保变量的顺序必须与结果集列的顺序相同:

关闭和释放游标 (Closing and deallocating cursor)

After consuming rows, you should close it to release the current result set and to free any cursor locks held on the rows on which the cursor is positioned. The command syntax is very simple, just write CLOSE keyword plus the name of the cursor as follows:

使用完行之后,应关闭它以释放当前结果集并释放在放置游标的行上保留的所有游标锁。 该命令的语法非常简单,只需编写CLOSE关键字以及游标的名称,如下所示:

CLOSE <Cursor_name>

After closing the cursor, you should make sure that the cursor object reference is released from the memory by using the DEALLOCATE command as following:

关闭游标后,应使用DEALLOCATE命令,确保从内存中释放了游标对象引用,如下所示:

DEALLOCATE <Cursor_name>

@@ FETCH_STATUS函数 (@@FETCH_STATUS function)

After illustrating the main commands used to manipulate SQL cursors, there are some system functions that support cursors such as @@FETCH_STATUS and @@CURSOR_ROWS. In this section, we will explain the @@FETCH_STATUS function by providing some examples.

在说明了用于操作SQL游标的主要命令之后,还有一些支持游标的系统函数,例如@@ FETCH_STATUS@@ CURSOR_ROWS 。 在本节中,我们将通过提供一些示例来说明@@ FETCH_STATUS函数。

什么是@@ FETCH_STAUTS函数? (What is the @@FETCH_STAUTS function?)

@@FETCH_STATUS is a system function that returns the status of the last FETCH statement issued against any opened cursor. This function returns an integer value as mentioned in the table below (Reference: @@FETCH_STATUS (Transact-SQL)):

@@ FETCH_STATUS是一个系统函数,它返回针对任何打开的游标发出的最后一个FETCH语句的状态。 该函数返回下表中提到的整数值(参考: @@ FETCH_STATUS(Transact-SQL) ):

Value

Description

0

The FETCH statement was successful

-1

The FETCH statement failed, or the row was beyond the result set

-2

The row fetched is missing

-9

The cursor is not performing a fetch operation

描述

0

FETCH语句成功

-1

FETCH语句失败,或者该行超出了结果集

-2

提取的行丢失

-9

游标未执行提取操作

One of the main use cases for this function is to implement it within a while loop to keep fetching rows while the fetch statement is successful instead of writing several FETCH statements for each cursor. As an example:

此函数的主要用例之一是在while循环中实现该函数,以在fetch语句成功执行时继续获取行,而不是为每个游标编写多个FETCH语句。 举个例子:

DECLARE @Schema NVARCHAR(50)
DECLARE @name NVARCHAR(50)DECLARE csr CURSOR FOR SELECT TABLE_SCHEMA, TABLE_NAME from INFORMATION_SCHEMA.TABLESOPEN csrFETCH NEXT FROM csr INTO @Schema, @nameWHILE @@FETCH_STATUS = 0BEGINFETCH NEXT FROM csr INTO @Schema, @nameENDCLOSE csr
DEALLOCATE csr

In the example above, we have created a SQL cursor to fetch the result of a SQL command that selects the name and the schema of tables created within the database. After declaring and opening the cursor, we issued the first FETCH statement. If the SQL query returned at least one row the first FETCH statement should be successful, else it should fail. After that, we used a WHILE loop to check if the FETCH statement was successful and to keep fetching rows while there are more rows to be fetched. When the FETCH statement doesn’t return any rows @@FETCH_STATUS function should return -1, and then the while loop is ended.

在上面的示例中,我们创建了一个SQL游标以获取一个SQL命令的结果,该命令选择在数据库内创建的表的名称和模式。 声明并打开游标后,我们发布了第一条FETCH语句。 如果SQL查询返回至少一行,则第一个FETCH语句应成功,否则应失败。 之后,我们使用WHILE循环来检查FETCH语句是否成功,并在需要提取更多行的同时继续获取行。 当FETCH语句不返回任何行时,@@ FETCH_STATUS函数应返回-1,然后while循环结束。

As mentioned in the previous section, it is very simple to give an example of how the @@FETCH_STATUS returns 0 and -1 values. But what about -2 and -9? In the next section, we will briefly explain these values by providing some examples.

如上一节所述,提供一个@@ FETCH_STATUS如何返回0和-1值的示例非常简单。 但是-2和-9呢? 在下一节中,我们将通过提供一些示例来简要解释这些值。

提取的行丢失(@@ FETCH_STATUS = -2) (The row fetched is missing (@@FETCH_STATUS = -2))

This FETCH status is returned if a row that should be returned in the FETCH statement is deleted in case that we used the KEYSET option while declaring the cursor (note that KEYSET option specifies that the membership and order of the rows in the cursor are fixed when the cursor is opened). This scenario happens when different users are working with the same data and one user deletes some rows while the other is trying to manipulate them using SQL cursor.

如果在声明游标的同时使用了KEYSET选项的情况下删除了应该在FETCH语句中返回的行,则会返回此FETCH状态(请注意,KEYSET选项指定了在以下情况下游标中行的成员资格和顺序是固定的:光标打开)。 当不同的用户使用相同的数据并且一个用户删除一些行而另一个用户试图使用SQL游标来操作它们时,会发生这种情况。

The following example is only to illustrate this scenario:

下面的示例仅用于说明这种情况:

DECLARE @Id intCREATE TABLE #TBLTEMP (Id int not null PRIMARY KEY)INSERT INTO #TBLTEMP (Id) VALUES (1),(2)DECLARE csr CURSOR KEYSET FOR SELECT Id FROM #TBLTEMP ORDER BY Id
OPEN Csr
FETCH NEXT FROM csr INTO @IdDELETE FROM #TBLTEMP WHERE Id = 2FETCH NEXT FROM csr INTO @IdSELECT @@FETCH_STATUS as [Fetch_Status]CLOSE csr
DEALLOCATE csr
DROP TABLE #TBLTEMP

As shown in the following screenshot you can see that the @@FETCH_STATUS function returned a value of -2:

如以下屏幕截图所示,您可以看到@@ FETCH_STATUS函数返回的值为-2:

For more information about KEYSET and other options that can be used while declaring SQL cursors you can refer to the following documentation: DECLARE CURSOR (Transact-SQL)

有关在声明SQL游标时可以使用的KEYSET和其他选项的更多信息,请参考以下文档: DECLARE CURSOR(Transact-SQL)

游标未执行获取操作(@@ FETCH_STATUS = -9) (The cursor is not performing a fetch operation (@@FETCH_STATUS = -9))

This value is not returned by the @@FETCH_STATUS function. It is a value stored within SQL Server internals and it is shown in the System Dynamic Management Views when the SELECT statement is defined. Declaring the SQL cursor will never fetch data (no information about the result set columns) regardless the cursor is open or not. The simplest example is to declare a cursor with a SELECT query that has no columns and only select NULL:

@@ FETCH_STATUS函数不会返回此值。 它是一个存储在SQL Server内部的值,并且在定义SELECT语句时显示在系统动态管理视图中。 无论游标是否打开,声明SQL游标都将永远不会获取数据(没有关于结果集列的信息)。 最简单的示例是使用没有列且仅选择NULL的SELECT查询声明一个游标:

DECLARE csr CURSOR FOR SELECT null FROM INFORMATION_SCHEMA.TABLESOPEN csr SELECT fetch_status from sys.dm_exec_cursors(@@SPID) WHERE name = 'csr'CLOSE csr
DEALLOCATE csr

As shown in the following screenshot, the result will show -9:

如以下屏幕截图所示,结果将显示为-9:

Note that, if you try to issue a FETCH statement it will return 0 or -1 regardless of the number of rows in the result set:

请注意,如果您尝试发出FETCH语句,则无论结果集中的行数如何,它都将返回0或-1:

For more information about system dynamic management views in SQL Server and sys.dm_exec_cursors, you can refer to the following links:

有关SQL Server和sys.dm_exec_cursors中的系统动态管理视图的更多信息,您可以参考以下链接:

  • System Dynamic Management Views 系统动态管理视图
  • Sys.dm_exec_cursors (Transact-SQL) Sys.dm_exec_cursors(Transact-SQL)

Also, you can refer to the following Stackoverflow.com posts for more information about @@FETCH_STATUS:

另外,您可以参考以下Stackoverflow.com帖子,以获取有关@@ FETCH_STATUS的更多信息:

  • What are the examples for @@fetch_status value -2 and -9 @@ fetch_status值-2和-9的示例是什么
  • What does the value -9 means for fetch_status in SQL Server? 值-9对SQL Server中的fetch_status意味着什么?

结论 (Conclusion)

In this article, we described briefly SQL cursor database object by illustrating the different phases in this object life cycle. In addition, we explained the @@FETCH_STATUS system function that is used to check the status of the FETCH statement of the cursor and we illustrated the different values that it returns by providing some scenarios that can yield for each value.

在本文中,我们通过说明该对象生命周期中的不同阶段来简要描述了SQL游标数据库对象。 另外,我们解释了@@ FETCH_STATUS系统函数,该系统函数用于检查游标的FETCH语句的状态,并通过提供一些可为每个值生成的方案来说明其返回的不同值。

翻译自: https://www.sqlshack.com/an-overview-of-the-sql-cursor-fetch_status-functions/

oracle游标fetch

oracle游标fetch_SQL游标@@ FETCH_STATUS函数概述相关推荐

  1. oracle表 游标,Oracle游标表达式和表函数

    Oracle游标表达式是Oracle数据库中的重要概念,下面就为您详细介绍Oracle游标表达式和表函数方面的知识,供您参考学习之用. Oracle游标表达式(有时称为游标子队列)是 SQL 语言的一 ...

  2. oracle实验使用游标,Oracle数据库实验-PLSQL游标、过程、函数、包的使用

    Oracle数据库基础 实验5 PL/SQL游标.过程.函数.包的使用 [实验学时] 2学时 [实验目的] 1.了解PL/SQL语言中显式游标和隐式游标的概念和属性. 2.了解显式游标和隐式游标的差异 ...

  3. 在oracle中游标的操作,Oracle中的游标和函数详解

    Oracle中的游标和函数详解 1.游标 游标是一种 PL/SQL 控制结构:可以对 SQL 语句的处理进行显示控制,便于对表的行数据 逐条进行处理. 游标并不是一个数据库对象,只是存留在内存中. 操 ...

  4. oracle中创建游标,oracle 存储过程创建游标

    Oracle与Sql Server差异点详解 1.create函数或存储过程异同点 Oracle 创建函数或存储过程一般是 create or replace -- SQL SERVER 则是在创建之 ...

  5. oracle中的cursor属性有哪些,Oracle学习11:游标(cursor)--显式游标隐式游标、游标四个属性、循环遍历...

    1.概述 上文PLSQL学习中提到的知识,可以发现,基本都可以通过Java等语言实现,而为了实现程序的可移植性,实际开发工作中我们也是如此做的. 那么PLSQL的重点是什么呢?接下来我们来介绍游标cu ...

  6. 小青蛙oracle跟踪,Oracle 存储过程:游标

    一.认识游标 什么是游标?游标是数据库的一种数据类型,它用来管理从数据源(表,视图等)获取到的数据结果集,可以想象成一个游动的光标(指针),指向一个结果集,通过游标的移动逐行提取每一行的记录,就像我们 ...

  7. oracle 记录给游标,Oracle游标 CURSOR实例详解

    一.游标概述: 游标(cursor)是数据库系统在内存中开设的一个数据缓冲区,存放SQL语句的执行结果. 每个游标都有一个名字,用户可以用SQL语句逐一从游标中获取记录,并赋给变量做进一步处理. 作用 ...

  8. oracle退出本循环,Oracle,跳出游标循环

    1,跳出游标的循环,不执行遍历了. 方法一:goto for c_row in 游标 loop if 条件 then dbms_output.put_line('测试跳出循环'); goto brea ...

  9. oracle 游标查询数据库,Oracle数据库使用游标查询结果集所有数据

    --Oracle使用游标查询结果集所有数据 DECLARE myTabelName NVARCHAR2(200):=''; --表名 myTableRowComment NVARCHAR2(200): ...

最新文章

  1. PHP - PDO 之 mysql 基础操作
  2. 【最简便解法】1086 就不告诉你 (15分)_13行代码AC
  3. Python 数据科学手册 5.8 决策树和随机森林
  4. QuickBI和DataV
  5. keepalived+LVS 详解(2) -- keepalived.conf解析
  6. STC学习:八位数码管滚动显示
  7. Layui组件和文档下载
  8. 微信小程序的下载安装
  9. 数据库中的日期相减_sql中两个日期相减
  10. 计算机内存die,从内存时序的角度告诉你 三星B-DIE为何成为高端所用
  11. 那些学校考846计算机,长安大学2021年考研846计算机类学科基础参考书目
  12. 打开本地html加载网页慢,浏览器打开网页很慢怎么回事_浏览器打开网页很慢如何解决...
  13. 如何使用API_api接口有什么优点
  14. OpenStack Victoria搭建(七)安装并验证 Placement
  15. SQL Server2012 学习之(一) :入门知识
  16. php stortm 老是闪退,pr加载界面闪退的原因是什么?
  17. 彭博社:Web3 巨大潜力之下的未解之谜
  18. 如何有效分配自己的精力
  19. [Excel VBA]判斷英文字母是否為大寫
  20. 单片机毕业设计 stm32智能温控风扇设计与实现 - 嵌入式 物联网

热门文章

  1. Source InSight context 窗口丢失的解决办法
  2. 前端页面数据埋点、分析和参考
  3. [ZJOI2008]骑士
  4. 如何将Android Studio项目提交(更新)到github
  5. hadoop ha 参考
  6. 第四周作业 简单地邮件发送实现
  7. centos 使用rz sz指令
  8. block,inline和inline-block
  9. QEMU+GDB调试方法
  10. 《Effective C#》Item 14:使用构造函数初始化语句