【问题标题】:Why can't I convert this varchar to numeric?为什么我不能将此 varchar 转换为数字?
【发布时间】:2017-08-09 15:42:31
【问题描述】:

我有一个粘贴了值的表,但它们最初以 varchar 开头。我需要将它们转换为数字,所以我做了

convert(decimal(10,3), cw.col7)

但这正在返回Error 8114: Error converting data type varchar to numeric。我提出这个问题的原因是因为它没有为类似的数据集给出这个错误。使用convert()decimal()时有时会出现奇怪的异常吗?还是我应该先转换为浮动?

数据:

col7

490.440 
2 
934 
28,108.000 
33,226.000 
17,347.000 
1,561.000 
57 
0 
421.350 
64 
1,100.000 
0 
0 
3,584 
202.432 
0 
3,280 
672.109 
1,150 
0 
104 
411.032 
18,016 
40 
510,648 
443,934.000 
18,705 
322,254 
301 
9,217 
18,075 
16,100 
395 
706,269 
418,313 
7,170 
40,450 
2,423 
1,300 
2,311 
94,000.000 
17,463 
0 
228 
884 
557 
153 
13 
0 
0 
212.878 
45,000.000 
152 
24,400 
3,675 
11,750 
987 
23,725 
268,071 
4,520.835 
286,000 
112,912.480 
9,000 
1,316 
1,020 
215,244 
123,967 
6,911 
1,088.750 
138,644 
16,924 
7,848 
33,017 
464,463 
618 
72,391 
9,367 
507,635.950 
588,087 
92,890 
17,266 
0 
1,414,547 
89,080 
664 
101,635 
1,552,992 
175 
356 
7,000 
0 
0 
445 
507,381 
24,016 
469,983 
0 
0 
147,737 
3,521 
88,210 
18,433.000 
21,775 
3,607 
34,774 
7,642 
42,680 
1,255 
10,880 
350,409.800 
19,394.520 
2,476,257.400 
778.480 
1,670.440 
9,710 
24,931.600 
3,381.800 
2,900 
18,000 
4,121 
3,750 
62,200 
952 
29.935 
17.795 
11.940 
902 
36,303 
1,240 
1,020 
617 
817 
620 
92,648 
70,925 
82,924 
19,162.200 
1,213.720 
2,871 
3,180 
91,600 
645 
607 
155,100 
6 
840 
1,395 
112 
6,721 
3,850 
40 
4,032 
5,912 
1,040 
872 
56 
1,856 
179 

【问题讨论】:

  • 去掉逗号再转换

标签: sql sql-server-2008 tsql sql-server-2008-r2 linqpad


【解决方案1】:

Try_Convert(money,...) 将处理逗号,而 decimal(10, 3) 将返回 null

示例

Select col7
      ,AsMoney   = Try_Convert(money,col7)
      ,AsDecimal = Try_Convert(decimal(10, 3),col7)
 from YourTable

退货

【讨论】:

  • 我忘了说 - 这个专栏不是货币。我可能需要显示 3 个以上的小数位,具体取决于。
  • @DarthVoid 我的回答是将值四舍五入到小数点后 4 位。如果您需要更多,那么 scaisEdge 的答案将是最好的。只需将小数(10,3)更改为适当的精度。
  • 我选择了这个。谢谢。
  • @DarthVoid 乐于助人
【解决方案2】:

尝试使用强制转换并删除逗号

 SELECT CAST(repalce(cw.col7,',','') AS DECIMAL(10,3))
 from your_table

根据 Jhon Cappelleti 的建议,您需要多于 3 位小数,因此您应该使用

 SELECT CAST(repalce(cw.col7,',','') AS DECIMAL(12,4))
 from your_table

【讨论】:

  • 我还为我的所有数据验证了isnumeric(cw.col7)=1
  • 然后显示 cw.col7 的内容 ... 可能不是数字或与 10,3 不兼容
  • OP 需要超过 4 位小数(与问题相反)Sooo...+1
  • @JohnCappelletti 非常感谢...用您的建议回答更新...赞成
【解决方案3】:

运行此查询:

select cw.col7
from cw
where try_convert(decimal(10, 3), cw.col7) is null;

这将显示未成功转换的值。 (如果cw.col7 可以是NULL 则添加and cw.col7 is not null 以使输出更有意义。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    相关资源
    最近更新 更多