Поясните смысл использования курсорной инструкции fetch напишите простой синтаксис этой инструкции

В этом учебном материале вы узнаете, как использовать оператор FETCH в Oracle/PLSQL c синтаксисом и примерами.

Описание

Цель использования курсора, в большинстве случаев, это получение строк из курсора таким образом, чтобы некоторый тип операций мог быть выполнен на данных. После объявления и открытия курсора, следующим шагом является выборка строк из курсора с помощью оператора FETCH.

Синтаксис

FETCH имя_курсора INTO variable_list;

Параметры или аргументы
имя_курсора наименование курсора, из которого вы хотите извлечь строки.
variable_list список переменных, разделенных запятыми, в которые вы хотите сохранить результирующий набор курсора.

Пример

Определим курсор таким образом.

CURSOR c1

IS

   SELECT course_number

   FROM courses_tbl

   WHERE course_name = name_in;

Команда, которая будет использоваться для выборки данных из этого курсор:

FETCH c1 into cnumber;

Эта команда выберет первое course_number в переменную cnumber.
Далее функция, которая показывает, как использовать оператор FETCH.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

CREATE OR REPLACE Function FindCourse

   ( name_in IN varchar2 )

   RETURN number

IS

   cnumber number;

   CURSOR c1

   IS

     SELECT course_number

     FROM courses_tbl

     WHERE course_name = name_in;

BEGIN

   OPEN c1;

   FETCH c1 INTO cnumber;

   if c1%notfound then

      cnumber := 9999;

   end if;

   CLOSE c1;

RETURN cnumber;

END;

FETCH is an SQL command used along with ORDER BY clause with an OFFSET(Starting point) to retrieve or fetch selected rows sequentially using a cursor that moves and processes each row one at a time till the number of rows mentioned in the query are displayed.

  • With FETCH the OFFSET clause is mandatory. You are not allowed to use, ORDER BY … FETCH.
  • You are not allowed to combine TOP with OFFSET and FETCH.
  • The OFFSET/FETCH row count expression can only be any arithmetic, constant, or parameter expression which will return an integer value.
  • With the OFFSET and FETCH clause, the ORDER BY is mandatory to be used. 

Syntax:

SELECT *

FROM table_name

ORDER BY col_name

OFFSET starting point

FETCH NEXT k(constant) ROWS ONLY;

Steps to implement FETCH:

Here, we will discuss the steps to implement the FETCH command in SQL. 

Step 1: Reference table: 

Let us consider a table is created based on marks of students in the class that contains data displayed below.

ID NAME MATHEMATICS PHYSICS CHEMISTRY
 501 Surya 99  97 85
502 Sravan 91  98 94
503 Charan 99  93 88
504 Ram 92  99 92
505 Aryan 94  99  88
506 Sathwik 91  88 91
507 Madhav 90  97 89

Step 2: Creating a database:

CREATE DATABASE gfg;

Step 3: Using the database:

USE gfg;

Step 4: Creating a table:

Creating table MarketList with 5 columns using the following SQL query:

CREATE TABLE MarkList
(
    id int,
    name varchar(20),
    mathematics int, 
    physics int,
    chemistry int
);

Step 5: Inserting the data into the table:

INSERT INTO MarkList VALUES(501,'Surya',99,97,85);
INSERT INTO MarkList VALUES(502,'Charan',99,93,88);
INSERT INTO MarkList VALUES(503,'Sravan',91,98,94);
INSERT INTO MarkList VALUES(504,'Ram',92,99,82);
INSERT INTO MarkList VALUES(505,'Aryan',94,99,88);
INSERT INTO MarkList VALUES(506,'Sathwik',91,88,91);
INSERT INTO MarkList VALUES(507,'Madhav',90,97,89);

Step 6: After inserting, the table will look like this.

Step 7: Now fetching the data using the fetch command: 

To retrieve the names, id and total marks of the top 3 students, the fetch command is used as follows:

SELECT Id, name, mathematics+physics+chemistry AS total
FROM MarketList
ORDER BY mathematics+physics+chemistry DESC
OFFSET 0 ROWS
FETCH NEXT 3 ROWS ONLY;

So, the SQL FETCH command is used to retrieve selected rows from a table sequentially. It’s handy to use when you want to select a limited number of rows from an ordered set, like top 3, top 10, or bottom 3, etc.

Last Updated :
19 May, 2021

Like Article

Save Article

С определениями, открытиями и закрытиями мы разобрались. Давайте, наконец, получим какие-нибудь результаты, т.е. данные. Собственно для чего и нужны курсоры. Выборка данных из курсора производится с помощью оператора FETCH. Пожалуй, он является ключевой фигурой в данном случае. Так как именно с его помощью происходит выборка из активного набора, сформированного при открытии курсора. После того как курсор открыт, данные в контекстной области SGA уже готовы, их остается только извлечь. Оператор
FETCH именно это и производит. Синтаксис его таков:

---------- FETCH - имя курсора - INTO - список переменных --------------
и
---------- FETCH - имя курсора - INTO - запись PL/SQL (%ROWTYPE) --------

Итак, переходим к практическим действиям. Запускаем наш старый добрый SQL*Plus. Запишем вот такой блок, используя пройденный материал:

DECLARE
	
	v_Office OFFICES.OFFICE%TYPE;
	v_City OFFICES.CITY%TYPE;
	
	CURSOR get_offices IS
		SELECT OFFICE, CITY 
		FROM OFFICES;

BEGIN

	OPEN get_offices; 
		-- Use operator FETCH to get variables!
		FETCH get_offices INTO v_Office, v_City;	
	
	CLOSE get_offices; 
	
END;
/

Получаем следующее:

SQL> DECLARE
  2  
  3   v_Office OFFICES.OFFICE%TYPE;
  4   v_City OFFICES.CITY%TYPE;
  5  
  6   CURSOR get_offices IS
  7       SELECT OFFICE, CITY
  8       FROM OFFICES;
  9  
 10  BEGIN
 11  
 12   OPEN get_offices;
 13    -- Use operator FETCH to get variables!
 14    FETCH get_offices INTO v_Office, v_City;
 15  
 16   CLOSE get_offices;
 17  
 18  END;
 19  /

Процедура PL/SQL успешно завершена.

Что ж, налицо правильная выборка, в две переменные первой строки активного набора. Но, как то не наглядно, не видно результата. Давайте немного перепишем наш предыдущий блок вот так:

SET SERVEROUTPUT ON

DECLARE
	
	v_Office OFFICES.OFFICE%TYPE;
	v_City OFFICES.CITY%TYPE;
	
	CURSOR get_offices IS
		SELECT OFFICE, CITY 
		FROM OFFICES;

BEGIN

	OPEN get_offices; 
		-- Use operator FETCH to get variables!
		FETCH get_offices INTO v_Office, v_City;	
		
		DBMS_OUTPUT.enable;
		DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
	CLOSE get_offices; 
	
END;
/

Получаем следующее:

SQL> SET SERVEROUTPUT ON

SQL> DECLARE
  2  
  3	v_Office OFFICES.OFFICE%TYPE;
  4	v_City OFFICES.CITY%TYPE;
  5  
  6	CURSOR get_offices IS
  7		SELECT OFFICE, CITY
  8		FROM OFFICES;
  9  
 10	BEGIN
 11  
 12	OPEN get_offices;
 13		-- Use operator FETCH to get variables!
 14		FETCH get_offices INTO v_Office, v_City;
 15  
 16		DBMS_OUTPUT.enable;
 17		DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
 18  
 19	CLOSE get_offices;
 20  
 21	END;
 22	/
OutPutString is: 22 Запиндрищинск                                               

Процедура PL/SQL успешно завершена.

Ура! Наконец-то мы видим результат! Давайте подробнее рассмотрим, что же произошло. Поле открытия курсора (не параметризованного) происходит выборка данных, согласно выражения SELECT курсора. Кстати легко проверить, что должен вернуть курсор просто выполнив его оператор SELECT, вот так:

SELECT OFFICE, CITY 
	FROM OFFICES
/

Получаем:

SQL> SELECT OFFICE, CITY
  2     FROM OFFICES
  3  /
  
 OFFICE CITY
------- -------------------
     22 Запиндрищинск
     11 Красный Мотоцикл
     12 Чугуевск
     13 Бубурино
     21 Котрогайка

5 строк выбрано

Это и есть ваш результирующий набор! Но здесь пять(!) строк скажете вы! Да! В таблице OFFICES пять записей, как вы помните из наших прошлых занятий. Но пример с FETCH вернул одну строку, потому что этот оператор производит выбор одной строки и смещает указатель в контекстной области на единицу. И ждет следующей команды на выборку. До тех пор, пока не будет достигнута последняя запись. Когда будет достигнута последняя запись, сработает атрибут курсора %NOTFOUND (его мы рассмотрим чуть позднее), он станет TRUE. Это значит, что все записи из результирующего набора выбраны! Но с помощью нашего примера можно выбрать и все пять записей, сделав вот так:

SET SERVEROUTPUT ON

DECLARE

	v_Office OFFICES.OFFICE%TYPE;
	v_City OFFICES.CITY%TYPE;
	
	CURSOR get_offices IS
		SELECT OFFICE, CITY 
		FROM OFFICES;

BEGIN

	OPEN get_offices; 

		DBMS_OUTPUT.enable;
		-- Use operator FETCH to get variables!
		FETCH get_offices INTO v_Office, v_City;	-- 1
		DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
		FETCH get_offices INTO v_Office, v_City;	-- 2
		DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
		FETCH get_offices INTO v_Office, v_City;	-- 3
		DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
		FETCH get_offices INTO v_Office, v_City;	-- 4
		DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
		FETCH get_offices INTO v_Office, v_City;	-- 5
		DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);

	CLOSE get_offices; 

END;
/

Получаем:

SQL> SET SERVEROUTPUT ON
SQL> 
SQL> DECLARE
  2  
  3   v_Office OFFICES.OFFICE%TYPE;
  4   v_City OFFICES.CITY%TYPE;
  5  
  6   CURSOR get_offices IS
  7       SELECT OFFICE, CITY
  8       FROM OFFICES;
  9  
 10  BEGIN
 11  
 12   OPEN get_offices;
 13  
 14    DBMS_OUTPUT.enable;
 15    -- Use operator FETCH to get variables!
 16    FETCH get_offices INTO v_Office, v_City; -- 1
 17    DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
 18    FETCH get_offices INTO v_Office, v_City; -- 2
 19    DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
 20    FETCH get_offices INTO v_Office, v_City; -- 3
 21    DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
 22    FETCH get_offices INTO v_Office, v_City; -- 4
 23    DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
 24    FETCH get_offices INTO v_Office, v_City; -- 5
 25    DBMS_OUTPUT.put_line('OutPutString is: '||TO_CHAR(v_Office)||' '||v_City);
 26  
 27   CLOSE get_offices;
 28  
 29  END;
 30  /
OutPutString is: 22 Запиндрищинск                                               
OutPutString is: 11 Красный Мотоцикл                                            
OutPutString is: 12 Чугуевск                                                    
OutPutString is: 13 Бубурино                                                    
OutPutString is: 21 Котрогайка                                                  

Процедура PL/SQL успешно завершена.

Вот все пять записей, каждый последующий FETCH вернул по одной записи! Теперь понятно? Думаю, да! И если вы уже, наверное, догадались, что здесь просто напрашивается оператор цикла! Давайте для начала (просто для примера) применим, оператор LOOP EXIT WHEN и при этом немного изменим наш курсор, применив атрибут %ROWTYPE вот так:

SET SERVEROUTPUT ON

DECLARE
	
	CURSOR get_offices IS
		SELECT * FROM OFFICES;

	v_gt get_offices%ROWTYPE;

BEGIN

	OPEN get_offices;
		
	LOOP 

		EXIT WHEN get_offices%NOTFOUND;

		DBMS_OUTPUT.enable;
		-- Use operator FETCH to get variables!
		FETCH get_offices INTO v_gt;	
		DBMS_OUTPUT.put_line('Get Data: '||TO_CHAR(v_gt.OFFICE)||' '||v_gt.CITY||' '
		||v_gt.REGION||' '||TO_CHAR(v_gt.MGR)||' '||TO_CHAR(v_gt.TARGET)||' '||TO_CHAR(v_gt.SALES));
	
	END LOOP;

	CLOSE get_offices; 

END;
/

И наконец получаем:

SQL> SET SERVEROUTPUT ON
SQL>
SQL> DECLARE
  2  
  3   CURSOR get_offices IS
  4       SELECT * FROM OFFICES;
  5  
  6   v_gt get_offices%ROWTYPE;
  7  
  8  BEGIN
  9  
 10   OPEN get_offices;
 11  
 12   LOOP
 13  
 14    EXIT WHEN get_offices%NOTFOUND;
 15  
 16    DBMS_OUTPUT.enable;
 17    -- Use operator FETCH to get variables!
 18    FETCH get_offices INTO v_gt;
 19    DBMS_OUTPUT.put_line('Get Data: '||TO_CHAR(v_gt.OFFICE)||' '||v_gt.CITY||' '
 20    ||v_gt.REGION||' '||TO_CHAR(v_gt.MGR)||' '||TO_CHAR(v_gt.TARGET)||' '||TO_CHAR(v_gt.SALES));
 21  
 22   END LOOP;
 23  
 24   CLOSE get_offices;
 25  
 26  END;
 27  /
Get Data: 22 Запиндрищинск Запад 108 300 186,042                                
Get Data: 11 Красный Мотоцикл Восток 106 575 692,637                            
Get Data: 12 Чугуевск Восток 104 800 735,044                                    
Get Data: 13 Бубурино Восток 105 350 367,911                                    
Get Data: 21 Котрогайка Запад 108 725 835,915                                   
Get Data: 21 Котрогайка Запад 108 725 835,915                                   

Процедура PL/SQL успешно завершена.

Ура! Я вас поздравляю, мы наконец чуть забежав вперед, с применением оператора цикла и курсорного атрибута %NOTFOUND, наконец написали наш первый полноценный курсор! Который выбирает все данные из таблицы и выводит их на экран! Но, не думайте, что это все что касается курсоров! Это далеко не так! :)

FETCH — retrieve rows from a query using a cursor

Synopsis

FETCH [ direction ] [ FROM | IN ] cursor_name

where direction can be one of:

    NEXT
    PRIOR
    FIRST
    LAST
    ABSOLUTE count
    RELATIVE count
    count
    ALL
    FORWARD
    FORWARD count
    FORWARD ALL
    BACKWARD
    BACKWARD count
    BACKWARD ALL

Description

FETCH retrieves rows using a previously-created cursor.

A cursor has an associated position, which is used by FETCH. The cursor position can be before the first row of the query result, on any particular row of the result, or after the last row of the result. When created, a cursor is positioned before the first row. After fetching some rows, the cursor is positioned on the row most recently retrieved. If FETCH runs off the end of the available rows then the cursor is left positioned after the last row, or before the first row if fetching backward. FETCH ALL or FETCH BACKWARD ALL will always leave the cursor positioned after the last row or before the first row.

The forms NEXT, PRIOR, FIRST, LAST, ABSOLUTE, RELATIVE fetch a single row after moving the cursor appropriately. If there is no such row, an empty result is returned, and the cursor is left positioned before the first row or after the last row as appropriate.

The forms using FORWARD and BACKWARD retrieve the indicated number of rows moving in the forward or backward direction, leaving the cursor positioned on the last-returned row (or after/before all rows, if the count exceeds the number of rows available).

RELATIVE 0, FORWARD 0, and BACKWARD 0 all request fetching the current row without moving the cursor, that is, re-fetching the most recently fetched row. This will succeed unless the cursor is positioned before the first row or after the last row; in which case, no row is returned.

Note

This page describes usage of cursors at the SQL command level. If you are trying to use cursors inside a PL/pgSQL function, the rules are different — see Section 43.7.3.

Parameters

direction

direction defines the fetch direction and number of rows to fetch. It can be one of the following:

NEXT

Fetch the next row. This is the default if direction is omitted.

PRIOR

Fetch the prior row.

FIRST

Fetch the first row of the query (same as ABSOLUTE 1).

LAST

Fetch the last row of the query (same as ABSOLUTE -1).

ABSOLUTE count

Fetch the count‘th row of the query, or the abs(count)‘th row from the end if count is negative. Position before first row or after last row if count is out of range; in particular, ABSOLUTE 0 positions before the first row.

RELATIVE count

Fetch the count‘th succeeding row, or the abs(count)‘th prior row if count is negative. RELATIVE 0 re-fetches the current row, if any.

count

Fetch the next count rows (same as FORWARD count).

ALL

Fetch all remaining rows (same as FORWARD ALL).

FORWARD

Fetch the next row (same as NEXT).

FORWARD count

Fetch the next count rows. FORWARD 0 re-fetches the current row.

FORWARD ALL

Fetch all remaining rows.

BACKWARD

Fetch the prior row (same as PRIOR).

BACKWARD count

Fetch the prior count rows (scanning backwards). BACKWARD 0 re-fetches the current row.

BACKWARD ALL

Fetch all prior rows (scanning backwards).

count

count is a possibly-signed integer constant, determining the location or number of rows to fetch. For FORWARD and BACKWARD cases, specifying a negative count is equivalent to changing the sense of FORWARD and BACKWARD.

cursor_name

An open cursor’s name.

Outputs

On successful completion, a FETCH command returns a command tag of the form

FETCH count

The count is the number of rows fetched (possibly zero). Note that in psql, the command tag will not actually be displayed, since psql displays the fetched rows instead.

Notes

The cursor should be declared with the SCROLL option if one intends to use any variants of FETCH other than FETCH NEXT or FETCH FORWARD with a positive count. For simple queries PostgreSQL will allow backwards fetch from cursors not declared with SCROLL, but this behavior is best not relied on. If the cursor is declared with NO SCROLL, no backward fetches are allowed.

ABSOLUTE fetches are not any faster than navigating to the desired row with a relative move: the underlying implementation must traverse all the intermediate rows anyway. Negative absolute fetches are even worse: the query must be read to the end to find the last row, and then traversed backward from there. However, rewinding to the start of the query (as with FETCH ABSOLUTE 0) is fast.

DECLARE is used to define a cursor. Use MOVE to change cursor position without retrieving data.

Examples

The following example traverses a table using a cursor:

BEGIN WORK;

-- Set up a cursor:
DECLARE liahona SCROLL CURSOR FOR SELECT * FROM films;

-- Fetch the first 5 rows in the cursor liahona:
FETCH FORWARD 5 FROM liahona;

 code  |          title          | did | date_prod  |   kind   |  len
-------+-------------------------+-----+------------+----------+-------
 BL101 | The Third Man           | 101 | 1949-12-23 | Drama    | 01:44
 BL102 | The African Queen       | 101 | 1951-08-11 | Romantic | 01:43
 JL201 | Une Femme est une Femme | 102 | 1961-03-12 | Romantic | 01:25
 P_301 | Vertigo                 | 103 | 1958-11-14 | Action   | 02:08
 P_302 | Becket                  | 103 | 1964-02-03 | Drama    | 02:28

-- Fetch the previous row:
FETCH PRIOR FROM liahona;

 code  |  title  | did | date_prod  |  kind  |  len
-------+---------+-----+------------+--------+-------
 P_301 | Vertigo | 103 | 1958-11-14 | Action | 02:08

-- Close the cursor and end the transaction:
CLOSE liahona;
COMMIT WORK;

Compatibility

The SQL standard defines FETCH for use in embedded SQL only. The variant of FETCH described here returns the data as if it were a SELECT result rather than placing it in host variables. Other than this point, FETCH is fully upward-compatible with the SQL standard.

The FETCH forms involving FORWARD and BACKWARD, as well as the forms FETCH count and FETCH ALL, in which FORWARD is implicit, are PostgreSQL extensions.

The SQL standard allows only FROM preceding the cursor name; the option to use IN, or to leave them out altogether, is an extension.

После того, как курсор объявлен и открыт, каждая строка становится доступной по отдельности с помощью оператора FETCH. В этом операторе указывается, что именно нужно извлечь (столбцы), а также место для хранения извлечённых данных. Кроме того, оператор FETCH автоматически перемещает внутренний указать на строки в пределах курсора для извлечения следующей, а не одной и той же строки снова и снова.

Практический пример

Рассмотрим работу курсора c_vendors. Обратите внимание, что курсор начинается с оператора DECLARE, на этот раз в нём объявляется не только курсор, но и переменные, в которых требуется хранить данные. Эти переменные объявляются очень просто: сначала они именуются, а затем связываются с отдельными столбцами таблицы.

Далее определяется сам курсор c_vendors, а затем он открывается при помощи OPEN. Далее появляется оператор LOOP, который определяет блок циклически повторяющегося кода. Код, который расположен между LOOP и END LOOP, повторно выполняется до тех пор, пока не возникнет условие, вынуждающее выйти из цикла.

В этом цикле одна строка извлекается из курсора в указанные переменные с помощью оператора FETCH. Обратите внимание, что имена столбцов в этом операторе не указаны, и поэтому очень важен порядок следования столбцов. То есть, содержимое первого столбца будет сохранено в первой переменной, содержимое второго столбца во второй и т.д.

Оператор FETCH извлекает строки по очереди, и поэтому на каждом шаге цикла извлекается новая строка, а переменные обновляются новыми значениями из этой строки.

Чтобы прекратить этот цикл, используется оператор EXIT, который осуществляет выход из цикла и прекращает обработку данных в нём. Оператором EXIT можно воспользоваться в любом месте кода.

В нашем примере оператор EXIT WHEN c_vendors%notfound; расположен в конце цикла, указывая Oracle выйти из цикла, когда курсор c_vendors возвратит состояние notfound, указывающее на то, что извлекаемых строк больше не осталось.

DECLARE 
    - Объявление переменных
    v_vend_id vendors.vend_id%TYPE;
    v_vend_name vendors.vend_name%TYPE;
    v_vend_address vendors.vend_address%TYPE;

    -- Объявление курсора
    CURSOR c_vendors IS
        SELECT vend_id, vend_name, vend_address
        FROM vendors;

BEGIN

    -- Открываем курсор
    OPEN c_vendors;

    - Перебираем курсор в цикле
    LOOP

    -- Получаем строку
    FETCH c_vendors INTO
        v_vend_id, v_vend_name, v_vend_address

    -- Выходим из цикла, если извлекаемых строк больше не осталось
    EXIT WHEN c_vendors%notfound;

    END LOOP;

    - Закрываем курсор
    CLOSE c_vendors;

END;

Метки: Oracle, Курсоры.

Это тоже интересно:

  • Пояснения 5 к балансу инструкция по заполнению
  • Пояснения 5 дебиторская и кредиторская задолженность инструкция по заполнению
  • Пояс тяньши инструкция по применению
  • Пояс с магнитами для поясницы турмалиновый инструкция по применению
  • Пояс турмалиновый с магнитами инструкция по применению цена

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии