考虑以下XML文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<Input Control="1234567890">
<Patient>
<AccountID>johnsmith@gmail.com</AccountID>
<Name>
<Title>Mr</Title>
<First>John</First>
<Middle>J</Middle>
<Last>Smith</Last>
</Name>
<Addresses>
<Address Type="Billing">
<Line1>123 Main St</Line1>
<Line2>Unit #1</Line2>
<City>Anytown</City>
<State>MD</State>
<PostalCode>78470</PostalCode>
<Country>USA</Country>
<Zone>TR89</Zone>
<Address Type="Contact">
<Line1>55 Main St</Line1>
<City>Anytown</City>
<State>MD</State>
<PostalCode>78470</PostalCode>
<Country>USA</Country>
<Zone>TR89</Zone>
</Address>
</Addresses>
<Phones>
<Phone Type="Daytime">555-221-2525</Phone>
<Phone Type="Evening">555-355-1010</Phone>
</Phones>
<Selects>
<Select Name="Current">0</Select>
</Selects>
</Patient>
</Input>
我需要将XML(使用XPath / XQuery)“粉碎”到下表中:
Account Nam_Pr Nam_Fst Nam_Lst Adrs1Main Adrs2Main CityMain ...
1 Mr. John Smith 123 Main St Unit #1 Anytown
问题是,我需要使用Address Type =“Billing元素中的数据填充AdrsMain字段,只有它存在于文件中。否则,AdrsMain字段将从Address Type =”Contact“元素填充我怎么能做到这一点?
答案 0 :(得分:1)
事实证明它比我想象的要难一点,所以我会继续回答这个消息。我不记得xquery从属性要求我做任何转换为null因为(我认为)返回的值已经为null。因此,您可能需要将一些空字符串转换回null。幸运的是,我发现了一个名为nullif
的酷运算符。
但这就是想法。
create table docs ( id int primary key, xmlbit xml);
假设您的文档文件已添加 然后你可以做到
with things (BillingLine1,ContactLine1) as
(
SELECT
nullif(cast(xmlbit.query('data(/Input/Patient/Addresses/Address[@Type="Billing"]/Line1)') as varchar(100)),'') as BillingLine1,
nullif(cast(xmlbit.query('data(/Input/Patient/Addresses/Address[@Type="Contact"]/Line1)') as varchar(100)),'') as ContactLine1
from docs
)
select BillingLine1, ContactLine1, Coalesce(BillingLine1, ContactLine1) as needed from things;
演示:http://sqlfiddle.com/#!3/b3fbd/15
可能还有其他方法可以做到这一点。我有一种感觉,如果你真的想,你可以在xquery / xpath语句中做所有事情,甚至可能更有利,但我不确定。
编辑:请注意我投射到的varchars的大小;你可能需要调整以适应。