简体   繁体   English

将varchar转换为数字:将数据类型varchar转换为数字时出错

[英]varchar to numeric:Error converting data type varchar to numeric

I am trying to convert a column formatted in varchar to decimal(19,12) with the following line of code 我正在尝试使用以下代码行将以varchar格式设置的列转换为十进制(19,12)

ALTER TABLE [tablename]
ALTER COLUMN [columnname][format]

and get the following prompt: 并得到以下提示:

Msg 8114, Level 16, State 5, Line 25
Error converting data type varchar to numeric.

Has worked before like a charm. 以前像魅力一样工作过。 The issue here seems to be that the values in the column are 19 or so digit numeric values formatted as text. 这里的问题似乎是该列中的值是19个左右的数字数值,格式为文本。

I tried to create a new column, pasted shortened cell values (used the left() function) into it from the original column but that doesn't seem to do the trick either since the code above ends up occationally with the additional "Arithmetic overflow occurred." 我试图创建一个新列,将缩短的单元格值(使用left()函数)从原始列粘贴到该列中,但这似乎没有解决问题的方法,因为上面的代码以附加的“算术溢出”结尾发生了。” message. 信息。

When some of the rows have incorrect values, ALTER COLUMN would not work. 当某些行的值不正确时, ALTER COLUMN将不起作用。 A typical course of action goes like this: 典型的操作过程如下:

  1. Add a new column of the desired type 添加所需类型的新列
  2. Update the column with values that you would like to keep 使用您想要保留的值更新列
  3. Drop the old column 删除旧列
  4. Rename the new column 重命名新列

Step 2 would go like this: 步骤2将如下所示:

UPDATE MyTable
SET NewColumn =
    CASE WHEN ISNUMERIC(OldColumn)=1 AND DATALENGTH(OldColumn) <= 19 THEN
        CAST(OldColumn AS decimal(19,12))
    ELSE
        NULL
    END

You could also turn ANSI warnings off with SET ANSI_WARNINGS OFF command, which would let you run ALTER COLUMN ignoring data trunction errors. 您也可以使用SET ANSI_WARNINGS OFF命令关闭ANSI警告,这将使您可以忽略数据截断错误而运行ALTER COLUMN The drawback of this approach is that potential errors get ignored. 这种方法的缺点是潜在的错误会被忽略。 On the other hand, when you do conversion explicitly with a CASE expression you have an option to supply an alternative value for the error case (I used NULL above, but you can put any number you want). 另一方面,当您使用CASE表达式进行显式转换时,可以选择为错误情况提供替代值(我在上面使用了NULL ,但是您可以输入任意数字)。

Could you try to seperate your problem? 您能分开解决问题吗? This does work on SQL 2012: 这确实适用于SQL 2012:

set nocount on 
if object_id ('tempdb..#t1') is not null drop table #t1

create table #t1 (c1 varchar(100))

insert #t1 values ('1234567.8901234567890')
select * from #t1

alter table #t1
alter column c1 decimal(19,12) 

select * from #t1

If you play around a bit with the strings you easily can produce an arimetic overflow error. 如果您在弦乐上稍作改动,很容易会产生算术溢出错误。 But 'Error converting data type varchar to numeric' needs character or empty sting . 但是“将数据类型varchar转换为数字时出错”需要字符或空字符串

Maybe you can try with your data? 也许您可以尝试使用数据?

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

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