SQL更新,字符串为数字

时间:2012-02-15 11:16:14

标签: sql sql-server

在SQL Server数据库中,我必须更新一些字段,查询是(,是小数点分隔符):

UPDATE MyTbable 
SET 
Field1 =   CAST('111,11' AS DEC(18,4)),
Field2 =  CAST('222,22' AS DEC(18,4)),
Field3 =  CAST('333,33' AS DEC(18,4))
WHERE Id = '1'

我收到错误: 将数据类型varchar转换为数字时出错。我尝试使用强制转换,同样的问题

Field1,Field2和Field3是数字38,2

有什么想法吗?

谢谢,

3 个答案:

答案 0 :(得分:2)

取出逗号。

UPDATE MyTbable 
SET 
Field1 =  CAST(REPLACE('111,11',',','.') AS DEC(18,4)),
Field2 =  CAST(REPLACE('222,22',',','.') AS DEC(18,4)),
Field3 =  CAST(REPLACE('333,33',',','.') AS DEC(18,4))
WHERE Id = '1'

答案 1 :(得分:1)

删除查询中的逗号,如:

UPDATE MyTbable 
SET 
Field1 =   CAST('11111' AS DEC(18,4)),
Field2 =  CAST('22222' AS DEC(18,4)),
Field3 =  CAST('33333' AS DEC(18,4))
WHERE Id = '1'

或者您可以使用替换删除逗号:

replace('111,11',',','.')

答案 2 :(得分:1)

使用.代替,

UPDATE MyTbable 
SET 
  Field1 =  CAST('111.11' AS DEC(18,4)),
  Field2 =  CAST('222.22' AS DEC(18,4)),
  Field3 =  CAST('333.33' AS DEC(18,4))
WHERE Id = '1'

如果您想在之后以字符串和逗号选择这些值,请执行以下操作:

select replace(cast(Field1 as varchar(30)), '.',','),
       replace(cast(Field2 as varchar(30)), '.',','),
       replace(cast(Field2 as varchar(30)), '.',','),
where Id = '1'