[英]Convert nvarchar to numeric in MSSQL Server
I have a nvarchar column with a list of entries such as (including NULLs)-我有一个 nvarchar 列,其中包含一个条目列表,例如(包括 NULL)-
-1.00000
0.000000
0.010000
0.100000
0.500000
00000000
1.000000
1.500000
10.00000
10.50000
100.0000
1000.000
1001.000
1006.000
NULL
NULL
I want to convert this to a numeric field so that I can use this field to do some calculations.我想将其转换为数字字段,以便我可以使用此字段进行一些计算。 However, I get the following error message-但是,我收到以下错误消息-
Error converting data type nvarchar to float.将数据类型 nvarchar 转换为 float 时出错。
Can someone please help?有人可以帮忙吗?
Your data would appear to have values are not valid numeric values.您的数据似乎具有不是有效数值的值。 Use try_convert()
:使用try_convert()
:
select try_convert(numeric(38, 12), col)
This will return NULL
if there is a failure in the conversion.如果转换失败,这将返回NULL
。
You can find the values that fail the conversion by doing:您可以通过执行以下操作找到转换失败的值:
select col
from t
where try_convert(numeric(38, 12), col) is null and col is not null;
You need to use try_convert()
wherever you reference the column as a numeric.您需要在将列作为数字引用的任何地方使用try_convert()
。 Converting in the select
only applies to the select
.在select
转换仅适用于select
。
Just to demonstrate Gordon's method in case OP needs:只是为了演示戈登的方法,以防 OP 需要:
create table #test(val nvarchar(100));
insert into #test values
('-1.00000'),
('0.000000'),
('0.010000'),
('0.100000'),
('0.500000'),
('00000000'),
('1.000000'),
('1.500000'),
('10.00000'),
('10.50000'),
('100.0000'),
('1000.000'),
('1001.000'),
('1006.000'),
(NULL),
(NULL)
select val, TRY_CONVERT(numeric(38,12),val) as converted_val from #test
Use try_convert(numeric(38,5), [ColumnName])
使用try_convert(numeric(38,5), [ColumnName])
This will return NULL when it cannot convert the string.当它无法转换字符串时,这将返回 NULL。 If it can, it will be able to convert it to a numeric number如果可以,它将能够将其转换为数字
You can try the convert function in SQLServer:你可以试试SQLServer中的convert函数:
select Convert(float, "column_name") from TABLE
Empty fields are returned as 0.空字段返回为 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.