简体   繁体   English

MSSQL Server 2008-将Nvarchar转换为数字

[英]MSSQL Server 2008 - Convert Nvarchar to numeric

im using mssql 2008 and Im permanently failing to convert an nvarchar to numeric values. 我使用mssql 2008和即时通讯永久无法将nvarchar转换为数值。

Can you please advise? 你能给些建议么? I have different solutions I found over the www, but all of them are failing with the error message: 我在www上找到了不同的解决方案,但所有解决方案均失败并显示错误消息:

Msg 8114, Level 16, State 5, Line 15 Error converting data type nvarchar to numeric. 消息8114,级别16,状态5,第15行将数据类型nvarchar转换为数值时出错。

I have built an reduced example for demonstration purpose: 我为演示目的构建了一个简化的示例:

IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL 
DROP TABLE dbo.#temptable 

create table #temptable(
col1 nvarchar(10),
col2 numeric(10,5)
)
insert into #temptable values ('0,5','0')

select *,convert(numeric(18,2),col1)   from #temptable

 UPDATE #temptable
 SET col2 = CAST(col1 AS numeric(10,5))
 WHERE ISNUMERIC(col1) = 1


SELECT col1
, CASE ISNUMERIC(col1)
WHEN    1 THEN  CONVERT(numeric(18,2),col1)  
ELSE 0.00
END

from #temptable

I alreay found an strong hint whats going wrong... the issue seems to be related to the , as seperator while the SQL server expects an . 我发现一个有力的暗示是出了什么问题...问题似乎与SQL Server期望使用。作为分隔符有关。

if you change the following line to: 如果将以下行更改为:

insert into #temptable values ('0.5','0')

its working 它的工作

The problem is you are using ISNUMERIC(col1) = 1 which fails for a ton of cases like ISNUMERIC('1e4') or ISNUMERIC('$') or in your case, ISNUMERIC('1,000,000') . 问题是您正在使用ISNUMERIC(col1) = 1 ,这在很多情况下ISNUMERIC('1e4')失败,例如ISNUMERIC('1e4')ISNUMERIC('$')ISNUMERIC('1,000,000') Don't use ISNUMERIC in this fashion. 不要以这种方式使用ISNUMERIC

Instead, try this... 相反,请尝试此...

 UPDATE #temptable
 SET col2 = CAST(col1 AS numeric(10,5))
 WHERE col1 not like '%[^0-9.]%'

Use try_convert() in SQL Server 2012+: 在SQL Server 2012+中使用try_convert()

UPDATE #temptable
   SET col2 = TRY_CONVERT(numeric(10,5), col1)
   WHERE ISNUMERIC(col1) = 1;

SQL Server re-arranges expression valuation in a query. SQL Server在查询中重新排列表达式评估。 So, the CAST() might be implemented before the WHERE -- resulting in the error. 因此, CAST()可能在WHERE之前实现-导致错误。 You can make a similar change to the SELECT version of your query. 您可以对查询的SELECT版本进行类似的更改。

In SQL Server 2008, you should be able to do effectively the same thing using CASE : 在SQL Server 2008中,您应该可以使用CASE有效地执行相同的操作:

UPDATE #temptable
   SET col2 = (CASE WHEN ISNUMERIC(col1) = 1 THEN CONVERT(numeric(10, 5), col1) END)
   WHERE ISNUMERIC(col1) = 1;

Note: There may be cases where ISNUMERIC() returns "1", but the value cannot be converted (for instance, overflow). 注意:在某些情况下, ISNUMERIC()返回“ 1”,但是无法转换该值(例如,溢出)。 In that case, this version would still fail. 在这种情况下,该版本仍然会失败。

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

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