SlideShare a Scribd company logo
Introduction To SQL Unit 13 Modern Business Technology Introduction To TSQL Unit 13 Developed by Michael Hotek
Cursors A cursor is a name that is associated with a select statement SQL is a set oriented language which means that an operation is performed on all rows that meet a qualification Sometimes, due to business rules, you must process a result set one row at a time A cursor gives you this ability
Cursors Cursor consist of two parts cursor result set - result set of the associated select statement cursor position - a pointer to the current row in the result set A cursor allows a program to perform an action row by row on a result set instead of on the entire result set Provides the ability to delete or update a row based on cursor position Bridges the set orientation of an RDBMS and row oriented programming
Cursors There are four types of cursors Language - declared in a batch Server - declared in a stored procedure Client - declared in an open client app Execute - declared in an open client app Cursors are handled by SQL Server differently based on the type of cursor To the user, the effect of a cursor is the same regardless of type
Cursors There are five steps to using a cursor Declare the cursor for the select statement you are using Open the cursor Fetch each row into the cursor, repeating until the entire result set has been processed Close the cursor Deallocate the cursor to free up system resources
Cursors The last step is generally forgotten by most developers.  Make sure you deallocate any cursors when you have finished with them. A cursor is one of the most expensive operation that can be performed in terms of resource usage If a cursor is not deallocated, all of the resources that it used are still taken and are not available to any other processes
Declaring Cursors declare cursor_name cursor for select_statement [for {read only | update [of column_list]}] declare mycursor cursor for select * from titles  for read only The declare cursor can be the only statement in a batch The cursor can have two modes read only for update
Declaring Cursors The cursor name must be a valid name The select statement can consist of any number of clauses The select Must contain a from clause Can not contain a compute, for browse, or into The column_list is the list of columns defined as updateable
Declaring Cursors A cursor that is in read only mode does not allow deletes or updates For update is the default mode, but you should always explicitly state what mode the cursor is for Regardless of mode, the cursor will be placed in read only mde if the select statement contains distinct group by aggregate functions unions
Opening Cursors After declaring a cursor, the next step is to open the cursor Opening the cursor causes the select statement to be executed, make the result set available for processing, and positions the cursor pointer to the first row declare mycursor cursor for select * from titles  for read only open mycursor
Fetching Rows Once the cursor is opened, you are ready to begin fetching rows declare mycursor cursor for select * from titles  for read only open mycursor fetch mycursor The cursor determines which row can be updated or deleted based on the cursor position
Fetching Rows When you fetch rows, there are two global variables that are important @@rowcount @@fetch_status (MS SQL Server) @@sqlstatus (Sybase) As you fetch rows, the value in @@rowcount increases
Fetching Rows @@sqlstatus can have three values 0 successful fetch 1 error in fetch 2 no more to fetch @@fetch_status can also have three values 0 successful fetch -1 error in fetch or no more rows -2 fetched row doesn't exist
Fetching Rows To add to the flexibility, you can fetch the data into variables fetch cursor_name [into fetch_list] The list of variables must match the column list in the select statement declare @title_name  varchar(80) declare mycursor cursor for select title from titles for read only open mycursor fetch mycursor into @title_name
Close and Deallocate When you are done with the cursor, close and deallocate it close cursor_name deallocate cursor_name declare mycursor cursor for select title from titles for read only go declare @title_name  varchar(80) open mycursor fetch mycursor into @title_name close mycursor deallocate mycursor
Close and Deallocate SQL Server will close a cursor when you exit the session return from a stored procedure that declared the cursor Do not rely on this to clean up your cursors You can reopen a cursor after it has been closed without declaring it again only if you do not deallocate it open mycursor... close mycursor open mycursor… close mycursor deallocate mycursor
Example --The below code will display business books at an 8% increase declare @title_id  char(6), @type  char(12), @price  money --Declare cursor and perform initial fetch declare curbooks cursor for select title_id, title, price from titles where type = ‘mod_cook’ for read only  open curbooks fetch curbooks into @title_id, @type, @price --Loop through all of the rows while @@fetch_status = 0 begin select @title_id, @type, convert(money,@price*1.08) --Subsequent fetches fetch curbooks into @title_id, @type, @price end close curbooks deallocate curbooks --The code below is equivalent to the cursor select title_id, type, convert(money, price*1.08) from titles where type = ‘mod_cook’
Data Modification You can delete a row based on the cursor position Declare the cursor for update declare mycursor … for update open mycursor fetch mycursor delete … where current of mycursor
Data Modification For data modification based on cursor position, the table requires a unique index Even if a cursor is declared for update, you can not delete a row if the cursor's select statement contains a join clause or references a multi-table view
Data Modification You can also update data based on cursor position declare mycursor … for update open mycursor fetch mycursor update … where current of mycursor
Data Modification An update does not move the cursor position The same row can be updated more than once until the next fetch is performed You can update a multi-table view or joined tables only if the update is being performed on one table
Cautions Always specify for read only or for update Do not leave cursors open for a long time If the same operation is performed on every row in the result set, do not use a cursor Always close and deallocate your cursors
Unit 13 Review Cursor allow you to perform an operation one row at a time Cursors can have two modes: for read only for update The steps to using a cursor are: declare open fetch close deallocate @@rowcount and @@sqlstatus or @@fetch_status will give you information about your fetch operations For more flexibility, you can fetch data into variables You can delete or update data by using the where current of cursor_name clause Always close and deallocate your cursors
Unit 13 Exercises Time allotted for exercises is 1/2 hour

More Related Content

What's hot (13)

PPT
Sql DML
Vikas Gupta
 
PDF
Versioning
LiquidHub
 
ODP
Sql commands
Balakumaran Arunachalam
 
PDF
SQL Readable Outputs - Oracle SQL Fundamentals
MuhammadWaheed44
 
PPT
SQL DDL
Vikas Gupta
 
PPT
Review of SQL
Information Technology
 
PPT
Retrieving data using the sql select statement
Syed Zaid Irshad
 
PPTX
SQL Data Manipulation
khalid alkhafagi
 
PPTX
Where conditions and Operators in SQL
Raajendra M
 
PPTX
Sql modifying data - MYSQL part I
Ahmed Farag
 
Sql DML
Vikas Gupta
 
Versioning
LiquidHub
 
SQL Readable Outputs - Oracle SQL Fundamentals
MuhammadWaheed44
 
SQL DDL
Vikas Gupta
 
Review of SQL
Information Technology
 
Retrieving data using the sql select statement
Syed Zaid Irshad
 
SQL Data Manipulation
khalid alkhafagi
 
Where conditions and Operators in SQL
Raajendra M
 
Sql modifying data - MYSQL part I
Ahmed Farag
 

Viewers also liked (20)

ODP
Kleer - Agile Testing - Especificaciones por medio de Ejemplos usando Fitnesse
Kleer Agile Coaching & Training
 
PPTX
Calendario matemático
Anqie Ayala Gónqora
 
PPT
Dr neha surana on scope&limitationofhomeopathyforneurologicaldisorders
Dr Neha Surana
 
PPT
Lab15 tugjrel
Haliuka Ganbold
 
PPTX
Felix moreno venegas
Felix Alberto Moreno Venegas
 
PDF
Tubi̇sad 2014 e_ticaret-raporu
Mustafa Kuğu
 
PPTX
Lab16
Haliuka Ganbold
 
PPT
How to make_an_origami_crane
twistytwistlers1477
 
PPT
Razvoj i prezentacija na proekt
Cre8ive8
 
PDF
輔導傳統產業
twnewone1
 
DOCX
Belchique vip
Connect Business Network
 
PDF
Ebi.ferrier.2011 sdep
Jenny Christopher
 
PDF
5數位內容
twnewone1
 
PPT
Intro to tsql unit 8
Syed Asrarali
 
PPTX
Presentation3
Ioana Stanescu
 
PDF
Verbala stigar - föreläsning medalgon 15 juni 2011
Verbala Stigar
 
PPTX
Google
Xavier Bille
 
PPTX
Linkedin
Bobby Munster
 
Kleer - Agile Testing - Especificaciones por medio de Ejemplos usando Fitnesse
Kleer Agile Coaching & Training
 
Calendario matemático
Anqie Ayala Gónqora
 
Dr neha surana on scope&limitationofhomeopathyforneurologicaldisorders
Dr Neha Surana
 
Lab15 tugjrel
Haliuka Ganbold
 
Felix moreno venegas
Felix Alberto Moreno Venegas
 
Tubi̇sad 2014 e_ticaret-raporu
Mustafa Kuğu
 
How to make_an_origami_crane
twistytwistlers1477
 
Razvoj i prezentacija na proekt
Cre8ive8
 
輔導傳統產業
twnewone1
 
Ebi.ferrier.2011 sdep
Jenny Christopher
 
5數位內容
twnewone1
 
Intro to tsql unit 8
Syed Asrarali
 
Presentation3
Ioana Stanescu
 
Verbala stigar - föreläsning medalgon 15 juni 2011
Verbala Stigar
 
Google
Xavier Bille
 
Linkedin
Bobby Munster
 
Ad

Similar to Intro to tsql unit 13 (20)

PDF
Cursors
Isha Aggarwal
 
PPT
Intro to tsql unit 11
Syed Asrarali
 
PPT
Procedures andcursors
LakshmiSamivel
 
PPT
PL/SQL Stored Procedures And Cursors.ppt
sonaligaikwad281110
 
DOC
3963066 pl-sql-notes-only
Ashwin Kumar
 
PPTX
Oracle:Cursors
oracle content
 
PPTX
Oracle: Cursors
DataminingTools Inc
 
PPTX
SAS Macro
Sonal Shrivastav
 
PPTX
plsql tutorialhub....
Abhiram Vijay
 
PPTX
Day 6.pptx
atreesgalaxy
 
PPT
Cursors.ppt
Karthick Panneerselvam
 
PPTX
Cursors
Priyanka Yadav
 
PPT
Lecture 3. MS SQL. Cursors.
Alexey Furmanov
 
PPTX
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
PPTX
PL SQL.pptx in computer language in database
ironman82715
 
PPT
4 cursors
Babajan Baig
 
PDF
PLSQL CURSOR
Arun Sial
 
ODP
SQL Tunning
Dhananjay Goel
 
PPTX
PL/SQL___________________________________
NiharikaKeshari
 
Cursors
Isha Aggarwal
 
Intro to tsql unit 11
Syed Asrarali
 
Procedures andcursors
LakshmiSamivel
 
PL/SQL Stored Procedures And Cursors.ppt
sonaligaikwad281110
 
3963066 pl-sql-notes-only
Ashwin Kumar
 
Oracle:Cursors
oracle content
 
Oracle: Cursors
DataminingTools Inc
 
SAS Macro
Sonal Shrivastav
 
plsql tutorialhub....
Abhiram Vijay
 
Day 6.pptx
atreesgalaxy
 
Lecture 3. MS SQL. Cursors.
Alexey Furmanov
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
PL SQL.pptx in computer language in database
ironman82715
 
4 cursors
Babajan Baig
 
PLSQL CURSOR
Arun Sial
 
SQL Tunning
Dhananjay Goel
 
PL/SQL___________________________________
NiharikaKeshari
 
Ad

More from Syed Asrarali (13)

PPT
Intro to tsql unit 14
Syed Asrarali
 
PPT
Intro to tsql unit 15
Syed Asrarali
 
PPT
Intro to tsql
Syed Asrarali
 
PPT
Intro to tsql unit 12
Syed Asrarali
 
PPT
Intro to tsql unit 10
Syed Asrarali
 
PPT
Intro to tsql unit 9
Syed Asrarali
 
PPT
Intro to tsql unit 7
Syed Asrarali
 
PPT
Intro to tsql unit 6
Syed Asrarali
 
PPT
Intro to tsql unit 5
Syed Asrarali
 
PPT
Intro to tsql unit 4
Syed Asrarali
 
PPT
Intro to tsql unit 3
Syed Asrarali
 
PPT
Intro to tsql unit 2
Syed Asrarali
 
PPT
Intro to tsql unit 1
Syed Asrarali
 
Intro to tsql unit 14
Syed Asrarali
 
Intro to tsql unit 15
Syed Asrarali
 
Intro to tsql
Syed Asrarali
 
Intro to tsql unit 12
Syed Asrarali
 
Intro to tsql unit 10
Syed Asrarali
 
Intro to tsql unit 9
Syed Asrarali
 
Intro to tsql unit 7
Syed Asrarali
 
Intro to tsql unit 6
Syed Asrarali
 
Intro to tsql unit 5
Syed Asrarali
 
Intro to tsql unit 4
Syed Asrarali
 
Intro to tsql unit 3
Syed Asrarali
 
Intro to tsql unit 2
Syed Asrarali
 
Intro to tsql unit 1
Syed Asrarali
 

Recently uploaded (20)

PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
July Patch Tuesday
Ivanti
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 

Intro to tsql unit 13

  • 1. Introduction To SQL Unit 13 Modern Business Technology Introduction To TSQL Unit 13 Developed by Michael Hotek
  • 2. Cursors A cursor is a name that is associated with a select statement SQL is a set oriented language which means that an operation is performed on all rows that meet a qualification Sometimes, due to business rules, you must process a result set one row at a time A cursor gives you this ability
  • 3. Cursors Cursor consist of two parts cursor result set - result set of the associated select statement cursor position - a pointer to the current row in the result set A cursor allows a program to perform an action row by row on a result set instead of on the entire result set Provides the ability to delete or update a row based on cursor position Bridges the set orientation of an RDBMS and row oriented programming
  • 4. Cursors There are four types of cursors Language - declared in a batch Server - declared in a stored procedure Client - declared in an open client app Execute - declared in an open client app Cursors are handled by SQL Server differently based on the type of cursor To the user, the effect of a cursor is the same regardless of type
  • 5. Cursors There are five steps to using a cursor Declare the cursor for the select statement you are using Open the cursor Fetch each row into the cursor, repeating until the entire result set has been processed Close the cursor Deallocate the cursor to free up system resources
  • 6. Cursors The last step is generally forgotten by most developers. Make sure you deallocate any cursors when you have finished with them. A cursor is one of the most expensive operation that can be performed in terms of resource usage If a cursor is not deallocated, all of the resources that it used are still taken and are not available to any other processes
  • 7. Declaring Cursors declare cursor_name cursor for select_statement [for {read only | update [of column_list]}] declare mycursor cursor for select * from titles for read only The declare cursor can be the only statement in a batch The cursor can have two modes read only for update
  • 8. Declaring Cursors The cursor name must be a valid name The select statement can consist of any number of clauses The select Must contain a from clause Can not contain a compute, for browse, or into The column_list is the list of columns defined as updateable
  • 9. Declaring Cursors A cursor that is in read only mode does not allow deletes or updates For update is the default mode, but you should always explicitly state what mode the cursor is for Regardless of mode, the cursor will be placed in read only mde if the select statement contains distinct group by aggregate functions unions
  • 10. Opening Cursors After declaring a cursor, the next step is to open the cursor Opening the cursor causes the select statement to be executed, make the result set available for processing, and positions the cursor pointer to the first row declare mycursor cursor for select * from titles for read only open mycursor
  • 11. Fetching Rows Once the cursor is opened, you are ready to begin fetching rows declare mycursor cursor for select * from titles for read only open mycursor fetch mycursor The cursor determines which row can be updated or deleted based on the cursor position
  • 12. Fetching Rows When you fetch rows, there are two global variables that are important @@rowcount @@fetch_status (MS SQL Server) @@sqlstatus (Sybase) As you fetch rows, the value in @@rowcount increases
  • 13. Fetching Rows @@sqlstatus can have three values 0 successful fetch 1 error in fetch 2 no more to fetch @@fetch_status can also have three values 0 successful fetch -1 error in fetch or no more rows -2 fetched row doesn't exist
  • 14. Fetching Rows To add to the flexibility, you can fetch the data into variables fetch cursor_name [into fetch_list] The list of variables must match the column list in the select statement declare @title_name varchar(80) declare mycursor cursor for select title from titles for read only open mycursor fetch mycursor into @title_name
  • 15. Close and Deallocate When you are done with the cursor, close and deallocate it close cursor_name deallocate cursor_name declare mycursor cursor for select title from titles for read only go declare @title_name varchar(80) open mycursor fetch mycursor into @title_name close mycursor deallocate mycursor
  • 16. Close and Deallocate SQL Server will close a cursor when you exit the session return from a stored procedure that declared the cursor Do not rely on this to clean up your cursors You can reopen a cursor after it has been closed without declaring it again only if you do not deallocate it open mycursor... close mycursor open mycursor… close mycursor deallocate mycursor
  • 17. Example --The below code will display business books at an 8% increase declare @title_id char(6), @type char(12), @price money --Declare cursor and perform initial fetch declare curbooks cursor for select title_id, title, price from titles where type = ‘mod_cook’ for read only open curbooks fetch curbooks into @title_id, @type, @price --Loop through all of the rows while @@fetch_status = 0 begin select @title_id, @type, convert(money,@price*1.08) --Subsequent fetches fetch curbooks into @title_id, @type, @price end close curbooks deallocate curbooks --The code below is equivalent to the cursor select title_id, type, convert(money, price*1.08) from titles where type = ‘mod_cook’
  • 18. Data Modification You can delete a row based on the cursor position Declare the cursor for update declare mycursor … for update open mycursor fetch mycursor delete … where current of mycursor
  • 19. Data Modification For data modification based on cursor position, the table requires a unique index Even if a cursor is declared for update, you can not delete a row if the cursor's select statement contains a join clause or references a multi-table view
  • 20. Data Modification You can also update data based on cursor position declare mycursor … for update open mycursor fetch mycursor update … where current of mycursor
  • 21. Data Modification An update does not move the cursor position The same row can be updated more than once until the next fetch is performed You can update a multi-table view or joined tables only if the update is being performed on one table
  • 22. Cautions Always specify for read only or for update Do not leave cursors open for a long time If the same operation is performed on every row in the result set, do not use a cursor Always close and deallocate your cursors
  • 23. Unit 13 Review Cursor allow you to perform an operation one row at a time Cursors can have two modes: for read only for update The steps to using a cursor are: declare open fetch close deallocate @@rowcount and @@sqlstatus or @@fetch_status will give you information about your fetch operations For more flexibility, you can fetch data into variables You can delete or update data by using the where current of cursor_name clause Always close and deallocate your cursors
  • 24. Unit 13 Exercises Time allotted for exercises is 1/2 hour