我是游标的新手,所以我不确定我是否正确执行此操作,但我正在尝试遍历一个临时表 foreach 行并使用 Column_X 和来自变量的另一个值计算 Column_Y 的值。变量值是正确的,但我没有从游标中获取 Column_X 的值。见下文:
SQL:
DECLARE @id INT
DECLARE @val DECIMAL
DECLARE @percent DECIMAL
DECLARE my_cursor CURSOR FOR
SELECT a.Id, a.Val FROM #Temp_Tbl a
OPEN my_cursor
FETCH FROM my_cursor INTO @id, @val
WHILE @@FETCH_STATUS = 0
BEGIN
--@Total is of type DECIMAL & is populated previously
PRINT Convert(varchar,@id) + ': (' + Convert(varchar,@val) + '/' + Convert(varchar,@Total) + '),'
SELECT @percent = @val / @Total
UPDATE #Temp_Tbl SET PERCENT_OF = @percent WHERE Id = @id
FETCH NEXT FROM my_cursor INTO @id, @val
END
CLOSE my_cursor
DEALLOCATE my_cursor
结果:
| ID | Val | PERCENT_OF |
| 1 | 25 | 1 |
| 2 | 45 | 0 |
| 3 | 30 | 0 |
消息输出:
2: (1/200) --NOTE: It's not printing the first record but 1 does get updated in the
3: (0/200) --PERCENT_OF column in the first row & 0 in the second.
谁能告诉我这里哪里出错了?谢谢你的帮助。