十进制数据类型的SQL更新数字列

时间:2011-05-06 14:11:16

标签: sql sql-server casting

我正在尝试从decimal(10,2)更新numeric(5,2)类型的列,但该列保持为null并且我没有错误消息。

DECLARE @newDurationAsDec decimal(10,2) 
DECLARE @newDurationAsNum numeric(5,2)

--@newDurationAsDec is set by some logic from another table and holds the correct value e.g 2.00

set @newDurationAsNum = CAST(@newDurationAsDec AS numeric(5,2)) 
--selecting @newDurationAsNum contains the correct value e.g. 2.00

UPDATE table
SET Duration = @newDurationAsNum
WHERE ID = @ID AND
      Duration IS NULL AND
      OtherColumn = 'T'

不会重新导致错误,也不会更新列。将更新更改为选择将返回正确的行。谁能指出我的错误? 提前谢谢。

2 个答案:

答案 0 :(得分:3)

下面对我说得好。检查没有可能干扰事情的触发器。

如果您至少使用SQL Server 2005,则可以使用OUTPUT子句查看更新的行,如下所示。

CREATE TABLE #T
(
ID INT PRIMARY KEY,
Duration NUMERIC(5,2),
OtherColumn CHAR(1)
)

INSERT INTO #T VALUES (1,NULL,'T')

DECLARE @ID INT = 1
DECLARE @newDurationAsDec DECIMAL(10,2) = 2

DECLARE @newDurationAsNum NUMERIC(5,2)
SET @newDurationAsNum = CAST(@newDurationAsDec AS NUMERIC(5,2)) 
SELECT @newDurationAsNum

UPDATE #T
SET Duration = @newDurationAsNum
OUTPUT inserted.*, deleted.*
WHERE ID = @ID AND
  Duration IS NULL AND
  OtherColumn = 'T'

SELECT * FROM #T  

DROP TABLE #T

答案 1 :(得分:2)

运行选择以查看您要更新的内容。我嵌入了我的更新语句,如下所示,只需通过注释和取消注释代码行就可以轻松地从选择到来回移动

--UPDATE t
--SET Duration = @newDurationAsNum 
Select *,   @newDurationAsNum
FROM table t
WHERE ID = @ID AND
       Duration IS NULL AND
       OtherColumn = 'T'