SQL - CURSOR没有正确获取值

时间:2013-06-18 16:42:03

标签: sql sql-server-2008

我是游戏的新手所以我不确定我是否正确地执行此操作但是我正在尝试通过临时表循环行并使用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.

谁能告诉我哪里出错了?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

问题在于您使用DECIMAL而没有告诉它精确度和比例。你想要几位小数?您应该始终明确使用精度和比例。尝试这样的事情:

DECLARE @id INT
DECLARE @val DECIMAL(16,4)
DECLARE @percent DECIMAL(16,4)