每次更新时加值加1

时间:2018-11-09 10:38:14

标签: sql loops advantage-database-server

在Advantage中尝试更新临时表中的值,但每次加1。起始值必须比另一个表的最大值大一个,并且每次更新新行时,都会在其中添加一个。忽略除顶部的声明游标和@nevid字符串外的所有内容。我可以在临时表中填充它的evid列,但是它会向每条记录添加71,这是正确的下一个数字,但是我需要将其设为71,72,73等。我在哪里出错? >

DECLARE cur CURSOR;
DECLARE @nevid INTEGER;
DECLARE @startdate string;
DECLARE @starttime string;
DECLARE @expectedenddate string;
DECLARE @expectedendtime string;
DECLARE @enddate string;
DECLARE @endtime string;
@nevid = 
( 
       SELECT (max(evid)+1) 
       FROM   pcplevnt
);

SELECT * 
INTO   #tmpev 
FROM   <table>;open cur 
AS 
  SELECT * 
  FROM   #tmpev;
    WHILE
        FETCH cur do 
        UPDATE #tmpev 
        SET evid = cast(@nevid AS sql_char(4));SET @nevid = @nevid + 1;
    END WHILE;
close cur;

1 个答案:

答案 0 :(得分:1)

我已经建立了MVCE以重现并解决您的问题:

DECLARE cur    CURSOR;
DECLARE @nevid INTEGER;

TRY DROP TABLE #pcplevnt; CATCH ALL END TRY; 
TRY DROP TABLE #tmpev;    CATCH ALL END TRY; 

CREATE TABLE
  #pcplevnt
(
  evid INTEGER
);

DELETE FROM #pcplevnt;
INSERT INTO #pcplevnt (evid) SELECT 111 FROM system.iota;

SET @nevid = (
SELECT
  max(evid) + 1
FROM #pcplevnt
);

CREATE TABLE
  #tmpev
(
  id AUTOINC,
  evid NVARCHAR(4)
);

INSERT INTO
  #tmpev
(
  evid
)
      SELECT '1' FROM system.iota
UNION SELECT '2' FROM system.iota
UNION SELECT '3' FROM system.iota
;

OPEN cur AS SELECT * FROM #tmpev;

WHILE FETCH cur DO
  UPDATE
    #tmpev
  SET
    evid = CAST(@nevid AS SQL_CHAR(4))
  WHERE
    id = cur.id
  ;
  SET @nevid = @nevid + 1;
END WHILE;

CLOSE cur;

select * from #tmpev;

请注意循环内WHERE中的UPDATE条件:

  UPDATE
    #tmpev
  SET
    evid = CAST(@nevid AS SQL_CHAR(4))
  WHERE
    id = cur.id
  ;
  SET @nevid = @nevid + 1;

我添加了一个主键字段id,可以在循环内与之进行比较,以便一次只更新临时表的一行。