SlideShare a Scribd company logo
7.1 : Cursors SQL Server 2005
What is a cursor Types of cursors Working with cursors Declare cursor Open cursor Fetch cursor Close cursor Contents
Objectives At the end of this presentation you should be able to: Understand the concept of cursor Understand why cursor is  required in a database Understand the different types of cursors Working with cursor
What is a Cursor A cursor is a database object that helps in accessing and manipulating row by row data in a given result set. Cursor serves as a mechanism for an application  to operate on a single row or a small set of rows .
What is a Cursor (Continued) It allows specific rows to be retrieved from result set It allows the current row in result set to be modified Helps to navigate from the current row in the result set to a different row Allows data to be modified by other users to be visible in  the result set.
Types of Cursors Cursors can be classified as follows: Static Forward_only Keyset driven Dynamic
Types of cursors (Continued) Forward_only cursor is the one which doesn’t support backward scrolling .This cursor only fetches rows in a serial order ,i.e. from beginning of the result set till end. The rows from the database are retrieved only if these are explicitly fetched. The changes made by an  INSERT , UPDATE and DELETE operations  are  reflected only when the rows are fetched  from  cursors Forward_ only It is a cursor that does not reflect any kind of modification that has been made  either to the associated tables in the database or to  the result  set of the cursor itself. Hence, none of the  UPDATE,DELETE or INSERT  operations is reflected in the cursor unless it is closed and reopened Static Description Cursor Type
Types of Cursors (Continued) Description Cursor Type Dynamic cursors are cursors that reflect all the changes that have been made to the result set while scrolling through it . All changes caused by any of the  INSERT, UPDATE  or  DELETE   operations are reflected in these cursors Dynamic keyset driven cursors are cursors that show changes in the result set caused by UPDATE and DELETE statement while the cursor is open but do not reflect the changes caused by the INSERT operation Keyset  driven
To work with Cursors The following process defines the working of a cursor in SQL Server: The cursor needs to be defined and its attributes need to be set. The cursor needs to be opened The required rows need to be fetched from the cursor The data in the current row of the cursor can be  modified, if required
To Work with Cursors (Continued) User can define a cursor and its characteristics set by using the  DECLARE CURSOR  statement. To Declare Cursors   : Syntax DECLARE cursor_name[INSENSITIVE ] [SCROLL] CURSOR  FOR{select_statement | prepared statement} [FOR {READ ONLY |  UPDATE[OF column_list]}]
To Work with Cursors (Continued) To Open Cursor  : User can open a cursor using the  open statement. To Fetch Data  : Once a cursor has been opened, you can retrieve a specific row from the result set of the cursor.SQL Server provides the  FETCH  statement to accomplish the task. Syntax OPEN Cursor_name
To Work with Cursors (Continued) To Fetch Data :   Syntax To Close cursor  : User must close a cursor in order to release the resources held by it. A cursor can be closed with CLOSE statement Deallocate Cursor  : Will remove the cursor reference. When the cursor is deallocated and if it is the last reference, the structures of the cursor are released. FETCH [[NEXT|PRIOR|FIRST|LAST]FROM]cursor_name [using Descriptor :sqlda_struct |INTO : hvar[…]] CLOSE cursor_name DEALLOCATE cursor_name
Example 1 - Cursor declare @author_id  char(20) declare c2 cursor forward_only for select  au_id from authors open c2 fetch next from c2 into @author_id while @@fetch_status = 0 begin print @author_id fetch next from c2 into @author_id end close c2 deallocate c2
Example 2 - Cursor Declare example cursor keyset For select * from report Open example Fetch last from example Delete from report where id=2 Fetch relative -1 from example Select @@fetch_status Close example Deallocate example
Activity Time(60 minutes) Activity: 7.1 Create a cursor to retrieve and display the Publisher_ID and Publisher_Name from the Publisher table.  Activity 7.2 Create a Cursor which retrieves the Title, Type and Price from the Title table and displays the records one after the other in the following format. ----------------------------------------------------------------------- Title : The Busy Executives Database Guide Title Type : Business  Price : 19.99 -----------------------------------------------------------------------
Activity Time(60 minutes) continued Activity: 7.3 Create a cursor to update the Quantity of the Items in the Items Table for the Orders Ordered in the OrderDetail table. Hint: Use Nested Cursor (Cursor within a Cursor)
Questions & Comments

More Related Content

PPT
Intro to tsql unit 13
PPTX
MYSQL single rowfunc-multirowfunc-groupby-having
PPT
Sql select
PPTX
Sql modifying data - MYSQL part I
PPTX
MYSQL using set operators
PPT
Retrieving data using the sql select statement
PDF
Data Manipulation(DML) and Transaction Control (TCL)
PPTX
MYSql manage db
Intro to tsql unit 13
MYSQL single rowfunc-multirowfunc-groupby-having
Sql select
Sql modifying data - MYSQL part I
MYSQL using set operators
Retrieving data using the sql select statement
Data Manipulation(DML) and Transaction Control (TCL)
MYSql manage db

What's hot (19)

PPTX
MYSQL join
PPT
SQL select statement and functions
PPTX
1. dml select statement reterive data
PPTX
STRUCTURE OF SQL QUERIES
PPTX
MULTIPLE TABLES
PDF
View & index in SQL
PPTX
Oracle SQL DML Statements
PDF
Database Management System 1
PPT
SQL Introduction to displaying data from multiple tables
PPTX
SQL commands
PPT
Les01 (retrieving data using the sql select statement)
PDF
SQL Functions - Oracle SQL Fundamentals
DOC
Adbms
PDF
SQL Readable Outputs - Oracle SQL Fundamentals
PPTX
Where conditions and Operators in SQL
PPT
Advanced Sql Training
PPTX
Creating database using sql commands
MYSQL join
SQL select statement and functions
1. dml select statement reterive data
STRUCTURE OF SQL QUERIES
MULTIPLE TABLES
View & index in SQL
Oracle SQL DML Statements
Database Management System 1
SQL Introduction to displaying data from multiple tables
SQL commands
Les01 (retrieving data using the sql select statement)
SQL Functions - Oracle SQL Fundamentals
Adbms
SQL Readable Outputs - Oracle SQL Fundamentals
Where conditions and Operators in SQL
Advanced Sql Training
Creating database using sql commands
Ad

Viewers also liked (20)

PPTX
Sql server ___________session3-normailzation
PPTX
Alasql.js - SQL сервер на JavaScript
PPT
SQL Server 2008 for .NET Developers
PPTX
SQL Server 2008 Spatial Data - Getting Started
PDF
High Performance Front-End Development
PPT
Module04
PPT
Module01
PPT
Module06
PDF
Transact sql data definition language - ddl- reference
PPTX
Alasql - база данных SQL на JavaScript (MoscowJS)
PDF
5 tsssisu sql_server_2012
PDF
Multidimensional model programming
PPT
SQL Server 2008 for Developers
PPT
Module02
PPT
Module08
PPTX
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
DOC
Css introduction
PPT
Module03
PDF
X query language reference
PDF
Multi-thematic spatial databases
Sql server ___________session3-normailzation
Alasql.js - SQL сервер на JavaScript
SQL Server 2008 for .NET Developers
SQL Server 2008 Spatial Data - Getting Started
High Performance Front-End Development
Module04
Module01
Module06
Transact sql data definition language - ddl- reference
Alasql - база данных SQL на JavaScript (MoscowJS)
5 tsssisu sql_server_2012
Multidimensional model programming
SQL Server 2008 for Developers
Module02
Module08
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
Css introduction
Module03
X query language reference
Multi-thematic spatial databases
Ad

Similar to Module07 (20)

PPT
Lecture 3. MS SQL. Cursors.
PDF
Cursors
PPTX
ADVANCED MODELLING.pptx
DOC
3963066 pl-sql-notes-only
PPTX
Sql tutorial
PPTX
Its about a sql topic for basic structured query language
PPTX
Cursors, triggers, procedures
PPTX
Data Manipulation Language.pptx
PPTX
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DOCX
Database object, sub query, Join Commands & Lab Assignment
PPTX
Adv.+SQL+PPT+final.pptx
PPTX
SQL Query
PPTX
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PPT
Scrollable Updatable
PPT
Scrollable Updatable
ODP
ODP
PDF
PLSQL CURSOR
PPT
Les08 (manipulating data)
PDF
java4th.pdf bilgisayar mühendisliği bölümü
Lecture 3. MS SQL. Cursors.
Cursors
ADVANCED MODELLING.pptx
3963066 pl-sql-notes-only
Sql tutorial
Its about a sql topic for basic structured query language
Cursors, triggers, procedures
Data Manipulation Language.pptx
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
Database object, sub query, Join Commands & Lab Assignment
Adv.+SQL+PPT+final.pptx
SQL Query
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
Scrollable Updatable
Scrollable Updatable
PLSQL CURSOR
Les08 (manipulating data)
java4th.pdf bilgisayar mühendisliği bölümü

Recently uploaded (20)

PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Classroom Observation Tools for Teachers
PPTX
master seminar digital applications in india
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Business Ethics Teaching Materials for college
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Pre independence Education in Inndia.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
RMMM.pdf make it easy to upload and study
PPTX
Cell Structure & Organelles in detailed.
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
102 student loan defaulters named and shamed – Is someone you know on the list?
Classroom Observation Tools for Teachers
master seminar digital applications in india
Microbial disease of the cardiovascular and lymphatic systems
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Business Ethics Teaching Materials for college
TR - Agricultural Crops Production NC III.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Pre independence Education in Inndia.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
01-Introduction-to-Information-Management.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Microbial diseases, their pathogenesis and prophylaxis
RMMM.pdf make it easy to upload and study
Cell Structure & Organelles in detailed.
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf

Module07

  • 1. 7.1 : Cursors SQL Server 2005
  • 2. What is a cursor Types of cursors Working with cursors Declare cursor Open cursor Fetch cursor Close cursor Contents
  • 3. Objectives At the end of this presentation you should be able to: Understand the concept of cursor Understand why cursor is required in a database Understand the different types of cursors Working with cursor
  • 4. What is a Cursor A cursor is a database object that helps in accessing and manipulating row by row data in a given result set. Cursor serves as a mechanism for an application to operate on a single row or a small set of rows .
  • 5. What is a Cursor (Continued) It allows specific rows to be retrieved from result set It allows the current row in result set to be modified Helps to navigate from the current row in the result set to a different row Allows data to be modified by other users to be visible in the result set.
  • 6. Types of Cursors Cursors can be classified as follows: Static Forward_only Keyset driven Dynamic
  • 7. Types of cursors (Continued) Forward_only cursor is the one which doesn’t support backward scrolling .This cursor only fetches rows in a serial order ,i.e. from beginning of the result set till end. The rows from the database are retrieved only if these are explicitly fetched. The changes made by an INSERT , UPDATE and DELETE operations are reflected only when the rows are fetched from cursors Forward_ only It is a cursor that does not reflect any kind of modification that has been made either to the associated tables in the database or to the result set of the cursor itself. Hence, none of the UPDATE,DELETE or INSERT operations is reflected in the cursor unless it is closed and reopened Static Description Cursor Type
  • 8. Types of Cursors (Continued) Description Cursor Type Dynamic cursors are cursors that reflect all the changes that have been made to the result set while scrolling through it . All changes caused by any of the INSERT, UPDATE or DELETE operations are reflected in these cursors Dynamic keyset driven cursors are cursors that show changes in the result set caused by UPDATE and DELETE statement while the cursor is open but do not reflect the changes caused by the INSERT operation Keyset driven
  • 9. To work with Cursors The following process defines the working of a cursor in SQL Server: The cursor needs to be defined and its attributes need to be set. The cursor needs to be opened The required rows need to be fetched from the cursor The data in the current row of the cursor can be modified, if required
  • 10. To Work with Cursors (Continued) User can define a cursor and its characteristics set by using the DECLARE CURSOR statement. To Declare Cursors : Syntax DECLARE cursor_name[INSENSITIVE ] [SCROLL] CURSOR FOR{select_statement | prepared statement} [FOR {READ ONLY | UPDATE[OF column_list]}]
  • 11. To Work with Cursors (Continued) To Open Cursor : User can open a cursor using the open statement. To Fetch Data : Once a cursor has been opened, you can retrieve a specific row from the result set of the cursor.SQL Server provides the FETCH statement to accomplish the task. Syntax OPEN Cursor_name
  • 12. To Work with Cursors (Continued) To Fetch Data : Syntax To Close cursor : User must close a cursor in order to release the resources held by it. A cursor can be closed with CLOSE statement Deallocate Cursor : Will remove the cursor reference. When the cursor is deallocated and if it is the last reference, the structures of the cursor are released. FETCH [[NEXT|PRIOR|FIRST|LAST]FROM]cursor_name [using Descriptor :sqlda_struct |INTO : hvar[…]] CLOSE cursor_name DEALLOCATE cursor_name
  • 13. Example 1 - Cursor declare @author_id char(20) declare c2 cursor forward_only for select au_id from authors open c2 fetch next from c2 into @author_id while @@fetch_status = 0 begin print @author_id fetch next from c2 into @author_id end close c2 deallocate c2
  • 14. Example 2 - Cursor Declare example cursor keyset For select * from report Open example Fetch last from example Delete from report where id=2 Fetch relative -1 from example Select @@fetch_status Close example Deallocate example
  • 15. Activity Time(60 minutes) Activity: 7.1 Create a cursor to retrieve and display the Publisher_ID and Publisher_Name from the Publisher table. Activity 7.2 Create a Cursor which retrieves the Title, Type and Price from the Title table and displays the records one after the other in the following format. ----------------------------------------------------------------------- Title : The Busy Executives Database Guide Title Type : Business Price : 19.99 -----------------------------------------------------------------------
  • 16. Activity Time(60 minutes) continued Activity: 7.3 Create a cursor to update the Quantity of the Items in the Items Table for the Orders Ordered in the OrderDetail table. Hint: Use Nested Cursor (Cursor within a Cursor)

Editor's Notes

  • #5: Faculty Notes : SQL server is very good at handling sets of data. For example : User can use a single SELECT statement to retrieve multiple rows of data. There are times when user wants to loop through a series of records to perform processing for each record .In this case user requires a cursor.
  • #8: Faculty notes: Static cursors are read only cursors .The result set of a static cursor is built in the tempdb database when it is opened.
  • #11: Faculty Notes : Cursor_name is the name of the cursor INSENSITIVE causes the result set to be stored in the tempdb database and does not permit the result set of the cursor to be modified. SCROLL specifies that the cursor can be positioned forwarded or backward to read the data. All the subsequent fetched display the modifications that have been made to underlying tables as long as the cursor is not declared using the INSENSITIVE option Select statement is a standard SELECT statement used for reterving rows from one or more tables. Prepared statement is the name of the prepared SQL SELECT statement READ ONLY prevents modification from taking place in the result set of the cursor. UPDATE[OF COLUMN_LIST] DEFINES THE UPDATEABLE COLUMNS WITHIN THE CURSOR. If the OF column_list option is used, then only the listed columns can be updated else all columns are updatable, unless the cursor has been defined as READ ONLY
  • #13: FACULTY NOTES: NEXT moves the cursor one row forward in the result set. This is the default action performed by the fetch statement. PRIOR returns the previous row in the result set and return it. FIRST moves the cursor to the first row in the result set and return it. LAST moves the cursor to the last row in the result set and return it FROM CURSOR_NAME is the name of the cursor from which the row(s) is to be fetched. INTO hvar are one or more host variables that store values returned by the FETECH statement. The number and the data type of the host variable must be identical to that of the columns used in the fetch statement. When a FETCH statement is executed the cursor is said to be positioned on the row that has been fetched. The fetched row is called the current row .If the cursor is not a READ ONLY cursor, then the current row in the underlying table can be modified or deleted by using the WHERE CURRENT OF clause. These operations on the current row are referred to as positioned operations. Closing Cursor: When a close statement is executed it leaves the structure of the cursor accessible for reopening However, the fetches and modifications are not possible unless the cursor is reopened.
  • #14: Faculty notes : The first Declare statement sets aside storage for one variables The OPEN statement gets the rows that the cursor declares The first FETCH NEXT statement gets the first row from the cursor @@fetch_status is a variable which will contain the value 0 if the previous fetch was successful. The print statement formats and prints the selected data for the user.
  • #15: Faculty notes The above example displays the value -2 for @@fetch_status, which means as the row for the id=2 is deleted and when you try to fetch that row ,it sets the value -2 to @@fetch_status. Before creating the above cursor, execute the following queries: create table report(id int primary key, name varchar(50)) insert into report values(1,'john') insert into report values(2,'tom') insert into report values(3,'peter') select * from report