In Advantage trying to update a value in a temp table, but adding 1 each time. The starting value needs to be one more than the max value from another table, and each time a new row is updated, one is added to that. Ignore all but the declare cursor and @nevid strings at the top. I can get it to populate the evid column in my temp table, but it adds 71 to each record, which is the correct next number, but I need it to be 71,72,73 etc. Where am I going wrong?
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;
I have build a MVCE to reproduce and fix your problem:
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;
Pay attention to the WHERE
condition in the UPDATE
inside of the loop:
UPDATE
#tmpev
SET
evid = CAST(@nevid AS SQL_CHAR(4))
WHERE
id = cur.id
;
SET @nevid = @nevid + 1;
I have added a primary key field id
that I can compare against inside the loop in order to only update one row of the temp table at once.