为什么我不能将此 varchar 转换为数字?

Why can't I convert this varchar to numeric?

我有一个 table,其中粘贴了值,但它们最初以 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 

尝试使用转换并删除逗号

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

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

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

运行 这个查询:

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

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

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

例子

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

Returns