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 Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SP NOT WORKING - HELP!

Status
Not open for further replies.

hinchdog

Programmer
Feb 14, 2001
380
US
This SP finds a record whose "current" column is true and set it to false, then moves to the next record and sets its "current" to true. However, if there is no next record (it's at the end of the table), then it is supposed to move to the first record and set "current" to true.

The SP works fine until it gets to the last record. I can't get the cusors to recognize that it at the end using @@FETCH_STATUS=2. What the heck am I doing wrong?? Very perplexed here!


CREATE PROC sp_ChangeAdmin
AS
BEGIN
DECLARE @ThisID INT
DECLARE @ThisCurrent BIT
DECLARE ThisAdmin CURSOR FOR
SELECT admin_id, admin_current
FROM admin

OPEN ThisAdmin
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH FROM ThisAdmin INTO @ThisID, @ThisCurrent
IF @ThisCurrent = 1
BREAK
ELSE
CONTINUE
FETCH NEXT FROM ThisAdmin
END
-- change current admin to normal
UPDATE admin SET admin_current=0 WHERE admin_id=@ThisID
-- get next admin
FETCH NEXT FROM ThisAdmin
-- check if end of records, if so start over
IF @@FETCH_STATUS=2
FETCH FIRST FROM ThisAdmin INTO @ThisID, @ThisCurrent
UPDATE admin SET admin_current = 1 WHERE admin_id = @ThisID

CLOSE ThisAdmin
DEALLOCATE ThisAdmin
END
 
Well, as noone responded, I was forced to figure it out by myself. Here's the working code incase anyone is interested :)

CREATE PROC sp_ChangeAdmin
AS
BEGIN
DECLARE @ThisID INT
DECLARE @ThisCurrent BIT
DECLARE ThisAdmin SCROLL CURSOR FOR
SELECT admin_current FROM admin FOR UPDATE

OPEN ThisAdmin
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM ThisAdmin INTO @ThisCurrent
IF @ThisCurrent = 1
BEGIN
-- change current admin to normal
UPDATE admin SET admin_current=0 WHERE CURRENT OF ThisAdmin
FETCH FROM ThisAdmin
BREAK
END
ELSE
CONTINUE
END

--check if not end of table (0), if not move next,
--if so start over
IF @@FETCH_STATUS= 0
FETCH NEXT FROM ThisAdmin
ELSE
FETCH FIRST FROM ThisAdmin
UPDATE admin SET admin_current = 1 WHERE CURRENT OF ThisAdmin

CLOSE ThisAdmin
DEALLOCATE ThisAdmin
END
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top