如何在SQL Server 2012中解析XML列?

时间:2016-11-09 20:56:54

标签: sql-server xml sql-server-2012

我从未在SQL Server中使用XML解析,我想在自己的列中提取字段,获取正确的数据。

我在CustomerHeaderUncompressed表中有一个名为Customer的列,如下所示,如何在SQL Server 2012中提取字段和数据?

<CustomerHeaderData>
<CustomerHeader>
    <shippingmethod Value="00000000-0000-0000-0000-000000000000" Name="" />
    <discount Value="" />
    <customdiscount Value="0" />
    <ponumber Value="9909933793" />
    <tax1 Value="-1" />
    <tax2 Value="-1" />
    <tax3 Value="0" />
    <tax3name Value="" />
    <tax4 Value="0" />
    <Freight />
    <ClientExtraField6 Value="5" />
    <ClientExtraField7 Value="3" />
    <dateneeded Value="01/01/0001 00:00:00" />
    <ClientTaxCodeSource>0</ClientTaxCodeSource>
    <shippingbranch />
    <dropnumber Value="" />
    <comment Value="" />
    <shippingzone Value="" />
    <salespersonID Value="704e78d4-cdbb-4963-bcc2-2c83a1d5f3fd" />
    <salesperson Value="Salesrep, XYZ" />
    <installation Value="False" />
    <salesterms Value="18" />
    <HeldItemDeliveryMethod Value="0" />
    <customcontrol>
        <CustomCustomerHeader CultureInfo="en-US">
            <BusinessSegment>TR</BusinessSegment>
            <BusinessSegmentID>1</BusinessSegmentID>
            <OrderType>2</OrderType>
            <MarketSegment>S3</MarketSegment>
            <CustomerDeliveryDate>2010-01-21</CustomerDeliveryDate>
            <BuildingPermitNumber />
            <FinalWallDepth />
            <PricingType>2</PricingType>
            <HouseBuiltBefore1978>False</HouseBuiltBefore1978>
            <AttributePricing>False</AttributePricing>
            <UndeterminedAttributes>False</UndeterminedAttributes>
            <EventIDStatus>VerifyFailed</EventIDStatus>
            <EventIDEnabled>False</EventIDEnabled>
            <CustomerDiscount>0</CustomerDiscount>
            <PreparedBy />
            <RequestedShipDate>01/14/2010</RequestedShipDate>
            <UserTestDate>01/01/0001</UserTestDate>
        </CustomCustomerHeader>
    </customcontrol>
</CustomerHeader>

1 个答案:

答案 0 :(得分:2)

基本上是这样的:

  • 从您的Customer
  • 中选择
  • 使用CROSS APPLY和XQuery .nodes()函数将XML作为XML片段的“动态”伪表(表别名XT),单列别名为{ {1}})
  • 使用XC XQuery函数
  • “到达”这些XML片段并提取所需的值;使用元素名称,属性需要以.value()符号为前缀

试试这个并将其扩展到您的需求:

@