FORWARD_ONLY and FAST_FORWARD Cursor example in SQL Server 2005:

My previous article was on cursors, it has covered different types of cursor with its definition. You can refer it at:

http://ritesh-a-shah.blogspot.com/2009/03/what-is-cursor-definition-of-cursor-in.html

As I promised in my above article that I will provide with some examples of cursor and here I am with example

–create one table for demo

use adventureworks

CREATE TABLE emps

(

Name VARCHAR(50),

Dept VARCHAR(10),

Company VARCHAR(15)

)

–INSERT records

INSERT INTO emps

SELECT ‘Ritesh’,‘MIS’,‘echem’ UNION ALL

SELECT ‘Bihag’, ‘MIS’, ‘CT’ UNION ALL

SELECT ‘Rajan’, ‘account’,‘Marwadi’ UNION ALL

SELECT ‘Alka’,‘account’,‘tata’ UNION ALL

SELECT ‘Alpesh’,‘Chemical’,‘echem’

GO

–script for FORWARD_ONLY Cursor

DECLARE @strName VARCHaR(15)

DECLARE FirstCur CURSOR FORWARD_ONLY

FOR SELECT Name FROM emps

OPEN FirstCur

FETCH FROM FirstCur INTO @strName

WHILE @@FETCH_STATUS=0

BEGIN

PRINT @strName

FETCH NEXT FROM FirstCur INTO @strName

END

CLOSE FirstCur

DEALLOCATE FirstCur

go

I have created one script for dynamic cross tab query in one of my previous article. I have used FAST_FORWARD cursor in that script. It will be nice example of cursor. You can refer it at

http://ritesh-a-shah.blogspot.com/2009/03/dynamic-cross-tab-query-with-cursor-in.html

Reference: Ritesh Shah

Advertisements

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

%d bloggers like this: