SQL Server Cursor Types - Forward Only Dynamic Cursor | SQL Server Tutorial / TSQL Tutorial

Cursors are the objects those allow us to access the data row by row from result set.

Forward Only Cursors do not allow backward scrolling. The only scrolling option we have is FETCH NEXT.

Forward only Static Cursors are sensitive to any changes ( update, delete, insert) made to original data source. If the changes are made, they will be extracted on Next Fetch.


Script for Forward_Only Dynamic Cursor


--drop table dbo.Customer
Create table dbo.Customer ( 
CustomerId Int Identity(1,1),
CustomerName VARCHAR(100),
StreetAddress VARCHAr(100),
City VARCHAR(100),
State CHAR(2))
go

--Insert couple of Records in Sample Table
Insert into dbo.Customer
Select 'Aamir shahzad','Test Street Address','Charlotte','NC'
Union 
Select 'M Raza','Test Street Address','Charlotte','NC'

Select * from dbo.Customer

--Insert NEW Record
Insert into dbo.Customer
Select 'John Smith','Test Street Address','New York City','NY'

--Delete Records
Delete from dbo.Customer
Where CustomerName in ('Aamir Shahzad','M Raza')

--Update All Record
Update dbo.Customer
set CustomerName='NO NAME'




--Cursor Script

Declare @CustomerID INT
Declare @CustomerNAme VARCHAR (100)
DECLARE @StreetAddress VARCHAR(100)
DECLARE @City VARCHAR(100)
DECLARE @State CHAR(2)

--DECLARE A CURSOR
DECLARE CUR CURSOR
Forward_Only Dynamic
FOR
Select CustomerID,CustomerName,StreetAddress,City,State from dbo.Customer

--OPEN CURSOR
OPEN CUR
Print 'CURSOR IS OPEN'
--FETCH NEXT RECORD
FETCH NEXT FROM CUR INTO @CustomerID,@CustomerNAme,@StreetAddress,@City,@State
WHILE @@FETCH_STATUS=0
BEGIN 
RAISERROR ('',0,1) WITH NOWAIT
WAITFOR DELAY '00:00:15'
PRINT CONCAT(@CustomerID,' ',@CustomerNAme,' ',@StreetAddress,' ',@City,' ',@State)
FETCH NEXT FROM CUR INTO @CustomerID,@CustomerNAme,@StreetAddress,@City,@State

END
CLOSE CUR
DEALLOCATE CUR



Watch the video for Forward Only Dynamic Cursor details in SQL Server


2 comments:

  1. in theory it should be forward only dynamic cursor are sensitive to any change

    ReplyDelete
  2. TODAY I GOT MY DESIRED XMAS LOAN AMOUNT $520,000.00 FROM A RELIABLE AND TRUSTED LOAN COMPANY. IF YOU NEED A LOAN NOW EMAIL CONTACT drbenjaminfinance@gmail.com

    Hello, I'm here to testify of how i got my loan from BENJAMIN LOAN FINANCE(drbenjaminfinance@gmail.com) I don't know if you are in need of an urgent loan to pay bills, start business or build a house, they offer all kinds of loan. So feel free to contact Dr. Benjamin Owen he holds all of the information about how to obtain money quickly and painlessly without cost/stress via Email: drbenjaminfinance@gmail.com

    Consider all your financial problems tackled and solved ASAP. Share this to help a soul right now THANKS.

    ReplyDelete