I’m very new to SQL Server. I’m using a cursor to populate a table with ids; I just discovered cursors today. The code is running but it is populating each row with the start value.
SET NOCOUNT ON
DECLARE @Irow int
declare @cheese int;
set @cheese = (select (max(balanceid) + 1) from balancetbl)
DECLARE aurum CURSOR FOR
SELECT @Irow
FROM aurumaugupload
OPEN aurum
FETCH aurum INTO @Irow
WHILE @@Fetch_Status = 0
BEGIN
update aurumaugupload set balanceid = @cheese
set @cheese = @cheese + 1;
FETCH aurum INTO @Irow
END
CLOSE aurum
DEALLOCATE aurum
RETURN
I think it’s a really basic error but I can’t see it due to my inexperience.
UPDATE: thanks guys for your prompts answers. I got it working after nonnb’s help. Here’s the final code:
SET NOCOUNT ON
DECLARE @acc int
declare @start int;
set @start = (select (max(balanceid) + 1) from balancetbl)
DECLARE aurum CURSOR FOR
SELECT accountid
FROM aurumaugupload
OPEN aurum
FETCH aurum INTO @acc
WHILE @@Fetch_Status = 0
BEGIN
update aurumaugupload set balanceid = @start where accountid = @acc
set @start = @start + 1;
FETCH aurum INTO @acc
END
CLOSE aurum
DEALLOCATE aurum
RETURN
There are at least 2 bugs here:
Bug 1
will select the same (unitialised) constant for every row of aurumaugupload
You need something like
Bug 2 – You are updating all rows within the cursor. You need a where