Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nvarchar to numeric in MSSQL Server

Tags:

sql

sql-server

I have a nvarchar column with a list of entries such as (including NULLs)-

-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.

Can someone please help?

like image 235
HM8689 Avatar asked Feb 15 '18 11:02

HM8689


3 Answers

Your data would appear to have values are not valid numeric values. Use try_convert():

select try_convert(numeric(38, 12), col)

This will return NULL if there is a failure in the conversion.

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. Converting in the select only applies to the select.

like image 93
Gordon Linoff Avatar answered Nov 01 '22 02:11

Gordon Linoff


Just to demonstrate Gordon's method in case OP needs:

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
like image 2
Prabhat G Avatar answered Nov 01 '22 03:11

Prabhat G


Use try_convert(numeric(38,5), [ColumnName])

This will return NULL when it cannot convert the string. If it can, it will be able to convert it to a numeric number

like image 1
SChowdhury Avatar answered Nov 01 '22 02:11

SChowdhury