Home
Services
Consultants
Technology
Contact Us
Price Guide
Link Exchange Program
SQL Server Tips
DBA Tips
Database Design
Database Migrations
Report Writing
BI & Data Warehouse Design
Web Application Development
Website Design
Database Optimisation
Remote DBA
T-SQL Cursors
T-SQL Database Design
T-SQL Functions and Procedures
T-SQL Cursors
T-SQL Cursors. When and when not to use them.
Forget cursors. I haven’t used them for years....
In the majority of situations where you would like to iterate through one way through a record set it makes sense just to create a temporary table with an identity field on it and two variables (@i and @maxi).
Now instead of going through the bother overhead and extra lines of code of declaring the cursor, opening the cursor, iterating though it and closing it, you can accomplish the same by a simple while loop and a few set statements.
Create table #temp
(
i int identity,
description varchar(max)
)
Insert into #temp (description)
Select ‘car’
Insert into #temp (description)
Select ‘bike’
Declare @i int
Declare @maxi int
Set @i = 1
Select @maxi = max(i) from #temp
While @i <= @maxi
Begin
Select * from #temp where i = @i
Set @i = @i + 1
End
Perhaps it’s just me but unless you need a cursor to do something specifically that couldn’t be done here I will continue using the much simpler and lightweight method above.
Last updated by admin1 on 7/27/2009
Login
|
Register