Cursor is a Temporary Memory or Temporary Work Station. It is Allocated by Database Server at the Time of Performing DML operations on Table by User. Cursors are used to store Database Tables. There are 2 types of Cursors: Implicit Cursors, and Explicit Cursors. These are explained as following below.
- Implicit Cursors:
Implicit Cursors are also known as Default Cursors of SQL SERVER. These Cursors are allocated by SQL SERVER when the user performs DML operations.
- Explicit Cursors :
Explicit Cursors are Created by Users whenever the user requires them. Explicit Cursors are used for Fetching data from Table in Row-By-Row Manner.
How to create Explicit Cursor:
- Declare Cursor Object.
Syntax : DECLARE cursor_name CURSOR FOR SELECT * FROM table_name
DECLARE s1 CURSOR FOR SELECT * FROM studDetails
- Open Cursor Connection.
Syntax : OPEN cursor_connection
- Fetch Data from cursor.
There are total 6 methods to access data from cursor. They are as follows :
FIRST is used to fetch only the first row from cursor table.
LAST is used to fetch only last row from cursor table.
NEXT is used to fetch data in forward direction from cursor table.
PRIOR is used to fetch data in backward direction from cursor table.
ABSOLUTE n is used to fetch the exact nth row from cursor table.
RELATIVE n is used to fetch the data in incremental way as well as decremental way.
Syntax : FETCH NEXT/FIRST/LAST/PRIOR/ABSOLUTE n/RELATIVE n FROM cursor_name
FETCH FIRST FROM s1 FETCH LAST FROM s1 FETCH NEXT FROM s1 FETCH PRIOR FROM s1 FETCH ABSOLUTE 7 FROM s1 FETCH RELATIVE -2 FROM s1
- Close cursor connection.
Syntax : CLOSE cursor_name
- Deallocate cursor memory.
Syntax : DEALLOCATE cursor_name
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Difference between View and Cursor in SQL
- Difference between Cursor and Trigger in DBMS
- Difference between Network and Relational data model
- Various types of Backup
- Self Join and Cross Join in MS SQL Server
- Delete statement in MS SQL Server
- Introduction of Shadow Paging
- Introduction of Standby Database
- Difference between Cloud Storage and Traditional Storage
- Various properties of CAP Theorem
- Difference between Hierarchical and Relational data model
- Difference between Hierarchical and Network Data Model
- SQL Error Messages
- Foreign key in MS SQL Server
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.