Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations dencom on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL/Server Cursor - Example of reason to use

Status
Not open for further replies.

Aluminum

Programmer
Jun 8, 2007
41
US
I cannot find an example online for a reason WHY you would need a cursor instead of an update statement. Does anyone have an example of a problem that can only be solved by using a cursor?
 
Tons of reasons when you could use a cursor, but generally you can replace them with derived tables, table variables or just rethinking your problem.

A sample example of when you could use a cursor is to loop through every table in a db outputting the contents. (I know you are likely never to want to do this but just giving an example as requested)

e.g.
Code:
DECLARE @tablename varchar(255), @sSQL varchar(2000)
	
DECLARE c1 CURSOR READ_ONLY
FOR
select name from sys.sysobjects where xtype = 'U'

OPEN c1

FETCH NEXT FROM c1
INTO @tablename

WHILE @@FETCH_STATUS = 0
BEGIN

	select @sSQL = 'SELECT * FROM ' + @tablename
        exec (@sSQL)

	FETCH NEXT FROM c1
	INTO @tablename

END

CLOSE c1
DEALLOCATE c1

Its just an example which cant "be replaced by a simple update"



"I'm living so far beyond my income that we may almost be said to be living apart
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top