Avoid Cursor in sql serve 2005

There is no need to explain much that using cursor in sql
script is an overhead . I am not saying that we can avoid cursors
completely but we can replace it with temp table in almost all
the places . Here is an small example to explain it ::::

DECLARE @ParamAliasName NVARCHAR(255)
DECLARE @columnName NVARCHAR(255)

DECLARE @ParamAliasName table
rownum INT IDENTITY (1, 1) Primary key NOT NULL ,
AliasKey NVARCHAR(255),


INSERT INTO @ParamAliasName (AliasKey)
SELECT pol.AliasKey FROM sometbl pol
–INNER JOIN wbsparam_tbl w on w.ParamID = pol.ParamID

SELECT @MaxRows=count(*) FROM @ParamAliasName

while @RowCnt <= @MaxRows
— do your cursor operation in this loop
SELECT @rc=0
SELECT @columnName=AliasKey, FROM @ParamAliasName
WHERE rownum = @RowCnt
SET @RowCnt = @RowCnt + 1 — increase count by 1


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s