开发者

Cursor not incrementing updating row with start value

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开发者_JAVA百科
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

DECLARE aurum CURSOR FOR
SELECT    @Irow
FROM      aurumaugupload

will select the same (unitialised) constant for every row of aurumaugupload You need something like

SELECT    Irow
FROM      aurumaugupload

Bug 2 - You are updating all rows within the cursor. You need a where

update aurumaugupload set balanceid = @cheese
where IRow = @IRow;

set @cheese = @cheese + 1


Your update statement doesn't have a where clause, so you are updating every row each time.


Try this solution (if the sorting/update order doesn't matter):

SET NOCOUNT ON
DECLARE  @Irow  int    
DECLARE @cheese int;
SET @cheese = (SELECT (MAX(balanceid) ) FROM balancetbl)

UPDATE aurumaugupload 
set    @cheese = balanceid = @cheese+1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜