FAST_FORWARD Cursor in SQL Server

The SQL FAST_FORWARD Cursor is one of the fastest cursors we have. This SQL FAST_FORWARD Cursor is a combination of FORWARD_ONLY, and READ_ONLY. It means the FAST_FORWARD cursor will only move from the first row to last and does not support the scrolling backward.

For this Create a FAST_FORWARD Cursor in SQL Server example, we use the below-shown Employee table that holds 14 records

FORWARD_ONLY Cursor in SQL Server 1

Fast_Forward Cursor in SQL Server Example

In this example, we show you how to declare and open a fast_forward cursor. And, we will use the different FETCH option to demonstrate the supporting fetch options.

-- SQL FAST_FORWARD Cursor Example

DECLARE fast_forward_employee_cursor CURSOR FAST_FORWARD
    FOR SELECT * FROM [EmployeeTable]
OPEN fast_forward_employee_cursor  
FETCH NEXT FROM fast_forward_employee_cursor;

Below statement will declare the fast_forward cursor called fast_forward_employee_cursor for all the records in Employee table

DECLARE fast_forward_employee_cursor CURSOR FAST_FORWARD
    FOR SELECT * FROM [EmployeeTable]

Next, we use the OPEN Cursor statement to open the declared cursor

OPEN fast_forward_employee_cursor

The last statement will fetch, or return the next record from the fast_forward_employee_cursor cursor.

FETCH NEXT FROM fast_forward_employee_cursor;

Although the employee table has 14 rows, this cursor is retrieving 1 record. This is because, SQL Server FETCH NEXT option will fetch only one record from the cursor, and if you want all then use Loops.

FAST_FORWARD Cursor in SQL Server 1

Next, we used the FETCH PRIOR option. As you can see, this is throwing an error.

FAST_FORWARD Cursor in SQL Server 2

Let me use the FETCH LAST option.

FAST_FORWARD Cursor in SQL Server 3

Let me use the FETCH FIRST option.

FAST_FORWARD Cursor in SQL Server 4

Please refer to FORWARD_ONLY Cursor article.

Categories SQL