Ошибка при преобразовании типа данных nvarchar в числовой

#sql-server #xml

#sql-сервер #xml

Вопрос:

У меня есть эта таблица в SQL Server:

 create table MobileUnit
(
    IDMobileUnit int identity  primary key,
    Type numeric null,
    Length numeric null,
    Width numeric null,
    Height numeric null
);
  

Моя задача — вставить XML-данные в эту таблицу, и я это сделал:

 <MobileUnit>
    <Type  />
    <Length  />
    <Width  />
    <Height  />
</MobileUnit>

INSERT INTO MobileUnit (Type, Length, Width, Height)
    SELECT 
        Type = c.value('Type[1]', 'numeric(18,0)'),
        Length = c.value('Length[1]', 'numeric(18,0)'),
        Width = c.value('Width[1]', 'numeric(18,0)'),
        Height = c.value('Height[1]', 'numeric(18,0)') 
    FROM 
        @xml.nodes('/NIACList/NIAC/CommercialUnit/MobileUnit') MobileUnit(c)
  

Проблема в том, что я получаю ошибку при выполнении кода

Ошибка преобразования типа данных nvarchar в числовой

Есть идеи, как решить эту проблему?

Комментарии:

1. Скорее всего, ваш формат ввода просто содержит некоторые строки в некоторых значениях …. сам по себе код выглядит нормально — при правильном вводе (все числа без дробных цифр) он работает нормально

2. ваши настройки Windows могут изменить ‘.’ и ‘,’ как десятичный разделитель.

Ответ №1:

Вы можете разделить значения XML как nvarchar(20), а затем использовать try_convert(), чтобы преобразовать их в числовой (18,0) или null …

 create table MobileUnit
(
    IDMobileUnit int identity  primary key,
    Type numeric null,
    Length numeric null,
    Width numeric null,
    Height numeric null
);

declare @xml xml =
'<NIACList>
 <NIAC>
  <CommercialUnit>
   <MobileUnit>
    <Type  />
    <Length  />
    <Width  />
    <Height  />
   </MobileUnit>
   <MobileUnit>
    <Type>1</Type>
    <Length>2</Length>
    <Width>3</Width>
    <Height>4</Height>
   </MobileUnit>
  </CommercialUnit>
 </NIAC>
</NIACList>';

INSERT INTO MobileUnit (Type, Length, Width, Height)
    SELECT 
        [Type] = try_convert(numeric(18, 0), c.value('Type[1]', 'nvarchar(20)')),
        Length = try_convert(numeric(18, 0), c.value('Length[1]', 'nvarchar(20)')),
        Width = try_convert(numeric(18, 0), c.value('Width[1]', 'nvarchar(20)')),
        Height = try_convert(numeric(18, 0), c.value('Height[1]', 'nvarchar(20)'))
    FROM 
        @xml.nodes('/NIACList/NIAC/CommercialUnit/MobileUnit') MobileUnit(c);

select * from MobileUnit;
  

Что дает результат…

 IDMobileUnit  Type  Length  Width  Height
           1  null    null   null    null
           2     1       2      3       4