Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Cursor help

Author  Topic 

cipriani1984
Constraint Violating Yak Guru

304 Posts

Posted - 2010-11-25 : 06:52:37
Hi,

I read through the section on this site to help with cursors, but just wanted an extended explaniation if possible.

so I have:

declare c1 cursor READ_ONLY
FOR
select USERNAME FROM INACTIVE_USERS

OPEN c1

FETCH NEXT FROM c1
INTO @user

WHILE @@FETCH_STATUS = 0
BEGIN

PRINT 'No Users'

FETCH NEXT FROM c1
INTO @user

-----

Does this cursor go through every user one at a time, or is it incrementing the users names into @user everytime?

thats the only thing i needed extra help with. Thanks :)

Lumbago
Norsk Yak Master

3271 Posts

Posted - 2010-11-25 : 07:08:37
Have you tried? It will iterate through the users one at a time... That being said: you should avoid using cursors altogether and use set-based methods instead. Whenever you consider using a cursor, think that "hey, I'm sure this could be done in a more effective way". 99% of the time you'll be right.

- Lumbago

My blog (yes, I have a blog now! just not that much content yet)
-> www.thefirstsql.com
Go to Top of Page

cipriani1984
Constraint Violating Yak Guru

304 Posts

Posted - 2010-11-25 : 07:09:50
Can you give me an example to a set based method?
Go to Top of Page

Lumbago
Norsk Yak Master

3271 Posts

Posted - 2010-11-25 : 07:22:47
Here is an example I stole from stackoverflow (http://stackoverflow.com/questions/24168/why-are-relational-set-based-queries-better-than-cursors):
--Cursor
DECLARE @phoneNumber char(7)
DECLARE c CURSOR LOCAL FAST_FORWARD FOR
SELECT PhoneNumber FROM Customer WHERE AreaCode IS NULL
OPEN c
FETCH NEXT FROM c INTO @phoneNumber
WHILE @@FETCH_STATUS = 0 BEGIN
DECLARE @exchange char(3), @areaCode char(3)
SELECT @exchange = LEFT(@phoneNumber, 3)

SELECT @areaCode = AreaCode
FROM AreaCode_Exchange
WHERE Exchange = @exchange

IF @areaCode IS NOT NULL BEGIN
UPDATE Customer SET AreaCode = @areaCode
WHERE CURRENT OF c
END
FETCH NEXT FROM c INTO @phoneNumber
END
CLOSE c
DEALLOCATE c
END

--Set
UPDATE Customer SET
AreaCode = AreaCode_Exchange.AreaCode
FROM Customer
JOIN AreaCode_Exchange ON
LEFT(Customer.PhoneNumber, 3) = AreaCode_Exchange.Exchange
WHERE
Customer.AreaCode IS NULL


- Lumbago

My blog (yes, I have a blog now! just not that much content yet)
-> www.thefirstsql.com
Go to Top of Page
   

- Advertisement -