问题是您WHERE
在更新查询中缺少一个子句,因此每个循环都在更新所有行。它应该是:
UPDATE sheet1$
SET new_id = @no1
WHERE New_ID = @No -- ONLY UPDATE 1 ROW
顺便说一句,假设您的 SQL-Server 标记是正确的,您可以使用ROW_NUMBER()
函数在没有光标的情况下执行此操作
WITH CTE AS
( SELECT New_ID, [RN] = ROW_NUMBER() OVER(ORDER BY New_ID)
FROM yourTable
)
UPDATE CTE
SET New_ID = RN
编辑 - 解释
ROW_NUMBER 只是提供了一个数字序列,Common Table Expression就像一个动态视图:
If you run:
WITH CTE AS
( SELECT New_ID, [RN] = ROW_NUMBER() OVER(ORDER BY New_ID)
FROM yourTable
)
SELECT *
FROM CTE
您应该更好地了解 CTE 中正在做什么,那么 CTE 的美妙之处在于您可以直接更新它们而无需参考回原始表,因此更新 CTE 相当于:
UPDATE yourTable
SET New_ID = RN
FROM yourTable
INNER JOIN
( SELECT New_ID, [RN] = ROW_NUMBER() OVER(ORDER BY New_ID)
FROM yourTable
) n
ON n.New_ID = yourTable.New_ID;