2016-11-09 53 views
1

我從來沒有在SQL Server中使用XML解析,我想提取自己的列中的字段,獲取正確的數據。如何解析SQL Server 2012中的XML列?

我在Customer表中有一個名爲CustomerHeaderUncompressed的列,如下所示,我如何提取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> 

+2

請將您的SQL code..here是可以幫助啓動ypi的鏈接http://stackoverflow.com/questions/3989395/convert-xml-to-table-sql-server – Hiten004

回答

2

基本上是這樣的:

  • Customer
  • 使用CROSS APPLY和XQuery的.nodes()功能選擇搶XML作爲 「上的即時」 XML片段的僞表(表別名XT,單列別名爲XC
  • 使用 .value() XQuery函數將
  • 「伸手可及」到這些XML片段中,並提取所需的值;使用元素名正因爲如此,和屬性需要用@標誌

前綴試試這個,它擴大到您的需求:

SELECT 
    ShippingMethodValue = XC.value('(shippingmethod/@Value)[1]', 'varchar(50)'), 
    ShippingMethodName = XC.value('(shippingmethod/@Name)[1]', 'varchar(50)'), 
    DiscountValue = XC.value('(discount/@Value)[1]', 'varchar(50)'), 
    CustomDiscountValue = XC.value('(customdiscount/@Value)[1]', 'varchar(50)'), 
    PONumber= XC.value('(ponumber/@Value)[1]', 'bigint') 
FROM 
    Customer 
CROSS APPLY 
    CustomerHeaderUncompressed.nodes('/CustomerHeaderData/CustomerHeader') AS XT(XC)