简体   繁体   English

SQL将nvarchar转换为float

[英]SQL convert nvarchar to float

I have a table with a column Quantity ; 我有一个带有“ Quantity列的表; in the original table this column is defined as nvarchar(100) so I need to cast it as float to be able to do some analysis: 在原始表中,此列定义为nvarchar(100)因此我需要将其强制转换为float以便进行一些分析:

CAST([Quantity] AS FLOAT) AS Quantity      

The issue is that I have some values which can not be converted to float like No-Quantity , Return etc. I to have filter to exclude these values and then convert rest to float.On option is use where clause: 问题是我有一些无法转换为float的值,例如No-QuantityReturn等。我有过滤器来排除这些值,然后将其余值转换为float.On选项使用where子句:

WHERE Quantity IN ('Return', 'Sales')

This is not the best way since if we have anew values in the original table then I need to figure out what it is and add it to the where clause. 这不是最好的方法,因为如果我们在原始表中有一个新值,那么我需要弄清楚它是什么并将其添加到where子句中。

I am wondering is there is better way to identify non-convertible values? 我想知道是否有更好的方法来识别不可转换的价值?

In any database, you can use cast() and something like this: 在任何数据库中,都可以使用cast()东西:

(case when quantity not in ('No-Quantity', 'Return', . . .)
      then CAST([Quantity] as float)
 end) as Quantity  

The in list would be the list of known string values. in列表将是已知字符串值的列表。

You can also do a fast-and-dirty check like this: 您还可以像这样进行快速和脏检查:

(case when left(quantity, 1) between '0' and '1'
      then CAST([Quantity] as float)
 end) as Quantity   

(Note: you may need to use substr() or substring() instead of left() .) (注意:您可能需要使用substr()substring()而不是left() 。)

And, in general, any specific database has specific functions that can help with the conversion, such as try_convert() mentioned in a comment. 而且,通常,任何特定的数据库都具有可以帮助转换的特定功能,例如注释中提到的try_convert()

If your SQL Server supports TRY_CONVERT , this could provide a nice solution: 如果您的SQL Server支持TRY_CONVERT ,则可以提供一个不错的解决方案:

SELECT TRY_CONVERT (float, [Quantity]) ...

will give you the converted values or NULL depending on the input. 会根据输入为您提供转换后的值或NULL。 This could be helpful if you don't have strict control over the data. 如果您不能严格控制数据,这可能会有所帮助。

Another way (if you can't use TRY_CONVERT ) 另一种方式(如果您不能使用TRY_CONVERT

SELECT CAST(quantity AS float)
FROM myTable
WHERE IsNumeric(quantity) = 1 AND quantity IS NOT NULL

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

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