Tuesday, November 4, 2008
How to use CURSOR in MSSQL
Hi,
Most of us sql lovers might be wondering on how to navigate in every row of a table treating the sql result set like a record set. Although I am sure that for those SQL Server experts, the word Cursor is too common for them and some would say that it would cause too much overhead. But just for the sake of those who don't know what cursor is, I have a basic tutorial for you guys.
-- First I would like to create a temporary table to help us on our tutorial.
Create Table tbl_Temp(
[RowNum] [int] NOT NULL,
[RowValue] [int] NOT NULL
)
Go
-- Next I will insert few records into the newly created table
Insert into tbl_Temp(RowNum,RowValue) values(1,50)
go
Insert into tbl_Temp(RowNum,RowValue) values(2,22)
go
Insert into tbl_Temp(RowNum,RowValue) values(3,11)
go
Insert into tbl_Temp(RowNum,RowValue) values(4,16)
go
Insert into tbl_Temp(RowNum,RowValue) values(5,23)
go
-- Here I need to create a variable that will serve as a storage
-- I want to have it as a varchar so that to avoid casting int values to varchar
Declare @RowNumStorage as varchar(3)
Declare @RowValueStorage as varchar(3)
-- Declare a cursor object that will serve as a pointer for the table tbl_Temp
Declare MyCursor cursor for
select * from tbl_Temp
-- Opening the cursor is important
-- It's like we didn't create any instance of the cursor at all if don't open it
open MyCursor
-- The lines below dictates the cursor to move to the next record
-- by default the cursor's current row location is set to -1
fetch next from MyCursor
into @RowNumStorage,@RowValueStorage
-- Check the row status of the cursor if it is not in the last row
while @@Fetch_Status =0
begin
-- Here I just need to show some displays to test if the cursor is really moving
-- I tried to check every row if the value is an ODD or EVEN number.
if((@RowValueStorage%2)=1)
begin
print 'RowNumber: ' + @RowNumStorage + ', Value:' + @RowValueStorage + ' is an ODD number '
end
else
begin
print 'RowNumber: ' + @RowNumStorage + ', Value:' + @RowValueStorage + ' is an EVEN number '
end
-- I need to call the fetch in order to loop through the record
FETCH NEXT FROM MyCursor
into @RowNumStorage,@RowValueStorage
end
-- finally I need to close the cursor and dispose it
close MyCursor
deallocate MyCursor
Subscribe to:
Post Comments (Atom)
2 comments:
I've been trying to study this kind of situation but I find it hard to understand.... but somehow your comments helped me a lot... tnx!
wla ko kasabot imo sample code....pls elaborate...
Post a Comment