简体   繁体   English

SQL Server - 将字符串转换为浮点数,并显示N / A.

[英]SQL Server - Convert String to float with N/A's present

I have a flat file that I loaded into SQL Server using the import wizard. 我有一个平面文件,我使用导入向导加载到SQL Server。 All columns are stored as nchar(50). 所有列都存储为nchar(50)。

I'm now trying to convert the table to a new table with various types (char, float, int, etc). 我现在正在尝试将表转换为具有各种类型的新表(char,float,int等)。

There is one column that I'd like to convert to float but it contains N/A strings. 有一列我想转换为float但它包含N / A字符串。

I checked that there weren't any other weird string using this: 我检查了没有任何其他奇怪的字符串使用这个:

SELECT col1, count(*)
from tab1
where ISNUMERIC(col1) <> 1
group by col1

Then I wrote a CASE statement to do the conversion: 然后我写了一个CASE语句进行转换:

SELECT CASE WHEN col1 = 'N/A' THEN NULL ELSE CAST(col1 AS FLOAT) END col1
INTO tab2
FROM tab1

But I'm getting this error message: 但我收到此错误消息:

Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.

Any idea what's causing this? 知道是什么导致了这个吗?

If 2012+ Use try_convert() 如果2012+使用try_convert()

SELECT col1, count(*)
from tab1
where try_convert(float,col1) is null
group by col1

如果要忽略浮动的无效字符,可以使用try_convert,如下所示

Select try_convert(float, col1) as col1 from yourtable

Careful on using ISNUMERIC() for this. 小心使用ISNUMERIC() It can return some false positives. 它可以返回一些误报。 For example... 例如...

select isnumeric('$')
select isnumeric('1e4') 

This should show you what is causing the error. 这应该会告诉你导致错误的原因。

select * from table where column like '%[^0-9\.]%' escape '\'

You can use this in a where clause, or use TRY_CONVERT() 您可以在where子句中使用TRY_CONVERT() ,或使用TRY_CONVERT()

You aren't doing the type conversion from the String to the float. 您没有进行从String到float的类型转换。 In your SQL statements you need to explicitly cast the original column type from nvarchar to float. 在SQL语句中,您需要将原始列类型从nvarchar显式转换为float。 Something like this might work: 像这样的东西可能会起作用:

SELECT
    CASE
        WHEN col1 = 'N/A' THEN NULL
        ELSE CAST(col1 AS FLOAT) 
    END col1
INTO tab2
FROM tab1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM