在SQL中使用IsNumeric时,将varchar转换为数字的算术溢出错误

时间:2017-01-27 03:28:13

标签: sql-server

当我尝试在临时表中插入小数时,我得到一个算术溢出错误:

  

将varchar转换为数据类型numeric的算术溢出错误。

这是SQL:

CREATE TABLE #ObDiabetesEncounterIDs
(
     PatientEncounterID int, 
     Value decimal(5,2)
)

INSERT INTO #ObDiabetesEncounterIDs(PatientEncounterID, Value)
    SELECT PatientEncounterID, Value 
    FROM Observation 
    WHERE Term = 'HGBA1C' 
      AND ISNUMERIC(Value) = 1 
      AND Value IS NOT NULL 
      AND PatientEncounterID IS NOT NULL;

大多数小数值介于5.1到15.1之间。有一些值是整数,如15和10.有2个超出该范围,如1405和151.我认为我使用数据类型decimal(5,2)来容纳这些值。

我哪里错了?

更新 更新小数的精度有帮助。这占了1403的1记录。但也有1个记录有逗号而不是句号。 所以,值是9,7。 所以,我相信我需要检查ISNUMERIC,然后将任何逗号更改为句点,然后转换为小数。

2 个答案:

答案 0 :(得分:0)

你的类型错了。 decimal(5,2)是小数点右边的3位数,左边是2位数。尝试将其更改为decimal(7,2)

答案 1 :(得分:0)

由于Value是字符数据,请将其转换为DECIMAL语句中的SELECT

CREATE TABLE #ObDiabetesEncounterIDs(PatientEncounterID int, Value decimal(7,2));

INSERT INTO #ObDiabetesEncounterIDs(PatientEncounterID, Value)
SELECT PatientEncounterID, CAST(Value AS DECIMAL(7,2))
  FROM Observation 
  WHERE Term = 'HGBA1C' 
    AND Value IS NOT NULL 
    AND PatientEncounterID IS NOT NULL;

为了测试这个,我做了以下(请注意,在以下示例中,我将源表MyObservation命名为Observation,而不是干扰原始表

CREATE TABLE [dbo].[MyObservation](
    [PatientEncounterID] [int] IDENTITY(1,1) NOT NULL,
    [Value] [varchar](50) NULL,
    [Term] [varchar](50) NULL,
    CONSTRAINT [PK_MyObservation] PRIMARY KEY CLUSTERED (
        [PatientEncounterID] ASC
    )WITH (
        PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON
    ) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO [dbo].[MyObservation]
    (Value, Term)
    Values ('.01', 'HGBA1C')
        ,('.12', 'HGBA1C')
        ,('1.23', 'HGBA1C')
        ,('12.34', 'HGBA1C')
        ,('123.45', 'HGBA1C')
        ,('1234.56', NULL)
        ,('12345.67', 'HGBA1C')
        ,('non-numeric', 'HGBA1C')
        ,('9.98', 'Not HGBA1C')
        ,('123.4958', 'HGBA1C')

CREATE TABLE #ObDiabetesEncounterIDs(
    PatientEncounterID int, Value decimal(7,2)
);

INSERT INTO #ObDiabetesEncounterIDs(PatientEncounterID, Value)
SELECT PatientEncounterID, CAST(Value AS DECIMAL(7,2))
    FROM [dbo].[MyObservation]
    WHERE Term = 'HGBA1C' 
    AND ISNUMERIC(Value) = 1
    AND Value IS NOT NULL 
    AND PatientEncounterID IS NOT NULL;

SELECT * FROM #ObDiabetesEncounterIDs

以上在我的SQL Server 2014系统上完美运行。