来自XML的SQL CAST

时间:2013-08-13 12:43:01

标签: sql-server xml tsql xpath sqlxml

我尝试CAST XML Value,例如0.19到INT并用* 100来计算它。

但我收到的错误如下: 在INT类型中转换nvarchar-Value'0.19'时出错。

这是代码:(但带有“CAST”的行是问题)

insert into BELEGP(Kennung, Belegtyp, Belegnummer, Posnummer, Postext, Zeilentyp, Menge, Steuerprozent, Eingabemenge, Editmenge, Artikelnummer, Bezeichnung, Preismenge, Einzelpreis, Gesamtpreis, Netto, Adressnr)

   SELECT  NEWID() as Kennung,
       'F' as Belegtyp,
       Myorder.j.value('OrderNumber[1]', 'varchar(50)') as Belegnummer,
       ROW_NUMBER() OVER (ORDER BY Myorder.j.value('OrderNumber[1]', 'varchar(50)')) as  Posnummer,
       ROW_NUMBER() OVER (ORDER BY Myorder.j.value('OrderNumber[1]', 'varchar(50)')) as  Postext,
       'A' as Zeilentyp,
       MyItem.j.value('Quantity[1]', 'varchar(50)') as Menge,
       CAST(Cast(MyItem.j.value('TaxRate[1]', 'nvarchar(50)') as nvarchar) as INT) * 100 as Steuerprozent,
       MyItem.j.value('Quantity[1]', 'varchar(50)') as Eingabemenge,
       MyItem.j.value('Quantity[1]', 'varchar(50)') as Editmenge,
       MyItem.j.value('Id[1]', 'varchar(50)') as Artikelnummer,
       MyItem.j.value('Name[1]', 'varchar(50)') as Bezeichnung,
       MyItem.j.value('TotalPrice[1]', 'varchar(50)') as Preismenge,
       MyItem.j.value('TotalPrice[1]', 'varchar(50)') as Einzelpreis,
       MyItem.j.value('TotalPrice[1]', 'varchar(50)') as Gesamtpreis,
       MyItem.j.value('UnityPrice[1]', 'varchar(50)') as Netto,
       Myorder.j.value('CustomerNumber[1]', 'varchar(50)') as Adressnr

   FROM (
 SELECT CAST(x AS XML)
 FROM
 OPENROWSET( BULK 'D:\shop\xml\Bestellungen.xml',SINGLE_BLOB) AS k(x))
 AS k(x)
 CROSS APPLY x.nodes('Orders/Order') AS MYorder(j)
 CROSS APPLY x.nodes('Orders/Order/Addresses/BillingAddress') AS MYAddresses(j)
 CROSS APPLY x.nodes('Orders/Order/LineItems/LineItem') AS MYItem(j)

1 个答案:

答案 0 :(得分:2)

即使您可以将值0.19转换为int,也会将其四舍五入为0.我认为您必须将值作为十进制获取,然后进行转换:

declare @Data xml = '<TaxRate>0.19</TaxRate>'
select cast(@Data.value('TaxRate[1]', 'decimal(29, 2)') * 100 as int)