游标不会使用起始值递增更新行

时间:2011-09-30 11:10:40

标签: sql-server cursor

我是SQL Server的新手。我正在使用游标来填充带有id的表;我今天刚刚发现了游标。代码正在运行,但它使用起始值填充每一行。

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

我认为这是一个非常基本的错误,但由于我的经验不足,我无法看到它。

更新:谢谢你的提示答案。在nonnb的帮助下我得到了它的工作。这是最终的代码:

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

3 个答案:

答案 0 :(得分:1)

您的更新语句没有where子句,因此您每次都要更新每一行。

答案 1 :(得分:1)

这里至少有2个错误:

错误1

DECLARE aurum CURSOR FOR
SELECT    @Irow
FROM      aurumaugupload

将为aurumaugupload的每一行选择相同的(单位化)常量 你需要像

这样的东西
SELECT    Irow
FROM      aurumaugupload

错误2 - 您正在更新游标中的所有行。你需要一个地方

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

set @cheese = @cheese + 1

答案 2 :(得分:0)

尝试此解决方案(如果排序/更新顺序无关紧要):

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

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