Home Forums Programming XML Importing XML in SQL Table RE: Importing XML in SQL Table

  • I don't use OPENXML often but knowing XPath makes this sort of thing pretty easy.  Here I'm using a variable for the XML so that you can copy/paste this to see how it works. This query:
    DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX)
    --SELECT @XML = XMLData FROM dwstage.[dbo].[OFSXMLFiles]

    SET @XML = '
    <appt_links>
    <appt_link>
    <Field name="ResourceID">38</Field>
    <Field name="FromActivityID">4545</Field>
    <Field name="FromActivityDate">2017-12-08</Field>
    <Field name="FromActivityRouteID">663</Field>
    <Field name="ToActivityID">4546</Field>
    <Field name="ToActivityDate">2017-12-08</Field>
    <Field name="ToActivityRouteID">663</Field>
    <Field name="Link Type" />
    </appt_link>
    </appt_links>';

    EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML

    SELECT xmlAttrib, xmlTxt
    FROM OPENXML(@hDoc, '/appt_links/appt_link/Field',1)
    WITH
    (
    xmlAttrib nvarchar(30) '@name',
    xmlTxt  nvarchar(30) '(text())[1]'
    );

    Returns:


    xmlAttrib                 xmlTxt
    ------------------------- ---------------
    ResourceID                38
    FromActivityID            4545
    FromActivityDate          2017-12-08
    FromActivityRouteID       663
    ToActivityID              4546
    ToActivityDate            2017-12-08
    ToActivityRouteID         663
    Link Type                 NULL

    All that's left to do is pivot these results. Here's how you do it, I only had time for a couple columns but this should be enough to help you across the finish line. 

    with x as
    (
    SELECT xmlAttrib, xmlTxt
    FROM OPENXML(@hDoc, '/appt_links/appt_link/Field',1)
    WITH
    (
      xmlAttrib nvarchar(30) '@name',
      xmlTxt  nvarchar(30) '(text())[1]'
    )
    )
    select 'ResourceID'  = max(case xmlAttrib when 'ResourceID' then xmlTxt end),
       'FromActivityID' = max(case xmlAttrib when 'FromActivityID' then xmlTxt end)
    from x;

    Returns

    ResourceID       FromActivityID
    --------------------- ------------------------------
    38                      4545

    (please forgive the sloppy formatting, the new SSC forum controls trip me up from time to time)

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001