Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Python Programs
    • Java Programs

FORWARD_ONLY Cursor in SQL Server

by suresh

The FORWARD_ONLY Cursor in SQL Server does not support scrolling. This SQL FORWARD_ONLY cursor can only move from the first row to last and does not support the other way (scrolling backward). It means the SQL FORWARD_ONLY Cursors support the FETCH_ONLY option, and it will return an error for all the remaining FETCH options.

SQL Server allows us to use the STATIC, DYNAMIC, or KEYSET keywords along with the FORWARD_ONLY Cursor. And if you omit any of these keywords, then SQL Server assumes it as DYNAMIC.

For this Create a forward_only Cursor in SQL Server demonstration, We use the below-shown table. As you can see, our Employee table holds 14 records

FORWARD_ONLY Cursor in SQL Server 1

Forward_Only Cursor in SQL Server Example 1

In this example, we will show you how to declare and open a forward_only cursor in SQL Server. And here, we will use the different FETCH options to demonstrate the supporting fetch options.

USE [SQL Tutorial]
GO

DECLARE forward_employee_cursor CURSOR FORWARD_ONLY
    FOR SELECT * FROM [EmployeeTable]
OPEN forward_employee_cursor  
FETCH NEXT FROM forward_employee_cursor;

ANALYSIS

Below statement will declare the forward_only cursor called forward_employee_cursor for all the records in Employee table

DECLARE forward_employee_cursor CURSOR FORWARD_ONLY
    FOR SELECT * FROM [EmployeeTable]

Below statement will open the declared cursor

OPEN forward_employee_cursor

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

FETCH NEXT FROM forward_employee_cursor;

OUTPUT

Although our employee table has 14 records, the cursor is retrieving one record. It is because SQL Server FETCH NEXT will fetch only one row from the cursor, and if you want all, then use Loops.

FORWARD_ONLY Cursor in SQL Server 2

Let me use the FETCH FIRST option. As you can see, this is throwing an error.

FORWARD_ONLY Cursor in SQL Server 3

Let me use the FETCH LAST option.

FORWARD_ONLY Cursor in SQL Server 4

Next, we used the FETCH PRIOR option.

FORWARD_ONLY Cursor in SQL Server 5

Forward_Only Cursor in SQL Server example 2

Let us see how to create FORWARD_ONLY STATIC Cursors and FORWARD_ONLY DYNAMIC Cursors. For this, we are using the DECLARE CURSOR Statement, and within that, we use the WHILE LOOP to loop over the cursor elements and perform updates

SET NOCOUNT ON
-- Declaring the Variables 
DECLARE @EmpID INT,
        @EmpName VARCHAR(50),
        @EmpEducation VARCHAR(50),
	@EmpOccupation VARCHAR(50),
	@EmpYearlyIncome DECIMAL (10, 2), 
	@EmpSales DECIMAL (10, 2);

DECLARE forward_employee_cursor CURSOR 
FORWARD_ONLY STATIC FOR 
	SELECT [ID]
	      ,[Name]
	      ,[Education]
	      ,[Occupation]
	      ,[YearlyIncome]
	      ,[Sales]
	FROM EmployeeTable
        ORDER BY Occupation

OPEN forward_employee_cursor
IF @@CURSOR_ROWS > 0
BEGIN 
      FETCH NEXT FROM forward_employee_cursor
            INTO @EmpID, @EmpName, @EmpEducation,
	         @EmpOccupation, @EmpYearlyIncome, @EmpSales
      WHILE @@FETCH_STATUS = 0
      BEGIN
	IF @EmpOccupation = N'Management'
 	    UPDATE [EmployeeTable] 
		SET [YearlyIncome] = 999999,
		    [Sales] = 15000
	    WHERE CURRENT OF forward_employee_cursor                
		
        FETCH NEXT FROM forward_employee_cursor
             INTO @EmpID, @EmpName, @EmpEducation,
	          @EmpOccupation, @EmpYearlyIncome, @EmpSales
      END
END
CLOSE forward_employee_cursor
DEALLOCATE forward_employee_cursor
SET NOCOUNT OFF 
GO

If you observe the cursor declaration, we are using the SQL FORWARD_ONLY STATIC cursor, and performing the UPDATE option.

We already explained the remaining steps in our previous article. I suggest you refer Dynamic Cursor in SQL Server, and Keyset Cursor examples.

FORWARD_ONLY Cursor in SQL Server 6

You can see that the error is stating: The Cursor is READ ONLY. It is because we mentioned the FORWARD_ONLY STATIC in the cursor declaration. And, STATIC Cursors does not support INSERT, DELETE, or UPDATE operations.

Please use the following SQL Query to check whether the Cursor has updated records in the Employee table or not.

USE [SQL Tutorial]
GO
SELECT [ID]
      ,[Name]
      ,[Education]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
  FROM [EmployeeTable]

OUTPUT

FORWARD_ONLY Cursor in SQL Server 7

Let me change the cursor declaration from static to dynamic by writing: FORWARD_ONLY DYNAMIC. Remember, it will work even if you forgot the DYNAMIC keyword because it is the default keyword for the forward_only trigger

FORWARD_ONLY Cursor in SQL Server 8

Now you can see the updated records.

FORWARD_ONLY Cursor in SQL Server 9

Placed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW
  • C Tutorial
  • C# Tutorial
  • Java Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQL Tutorial
  • SQL Server Tutorial
  • R Tutorial
  • Power BI Tutorial
  • Tableau Tutorial
  • SSIS Tutorial
  • SSRS Tutorial
  • Informatica Tutorial
  • Talend Tutorial
  • C Programs
  • C++ Programs
  • Java Programs
  • Python Programs
  • MDX Tutorial
  • SSAS Tutorial
  • QlikView Tutorial

Copyright © 2021 | Tutorial Gateway· All Rights Reserved by Suresh

Home | About Us | Contact Us | Privacy Policy