Quantcast
Channel: Welcome To TechBrothersIT
Viewing all articles
Browse latest Browse all 1979

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

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

Dynamic Cursors are update-able. The dynamic cursor will fetch the changes (insert,update or delete) on each fetch while cursor is open if any modification happened to original data in table/s. This type of Cursor is helpful when we want to extract the records from original table/s while cursor is open and we are still in process of modification of data or inserting new records and want to include them in cursor result set to perform operation.

Dynamic cursors are scrollable (First,Last,Prior,Next,Relative) but absolute option does not work with dynamic Cursors.

Script for Dynamic Cursor in SQL Server used in the video as well.


--drop table dbo.Customer
Createtable dbo.Customer (
CustomerId IntIdentity(1,1),
CustomerName VARCHAR(100),
StreetAddress VARCHAr(100),
City VARCHAR(100),
StateCHAR(2))
go

--Insert couple of Records in Sample Table
Insertinto 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
Insertinto dbo.Customer
Select'John Smith','Test Street Address','New York City','NY'

--Delete Records
Deletefrom 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 @StateCHAR(2)

--DECLARE A CURSOR
DECLARE CUR CURSOR
DYNAMIC
FOR
Select CustomerID,CustomerName,StreetAddress,City,Statefrom dbo.Customer

--OPEN CURSOR
OPEN CUR
Print'CURSOR IS OPEN'
--FETCH NEXT RECORD
FETCHNEXTFROM 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)
FETCHNEXTFROM CUR INTO @CustomerID,@CustomerNAme,@StreetAddress,@City,@State

END
CLOSE CUR
DEALLOCATE CUR

Please watch the video for Detail Demo of Dynamic Cursors in SQL Server.

Viewing all articles
Browse latest Browse all 1979

Trending Articles