Click here to Skip to main content
16,004,507 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi

I would like to transform the XML below into a SQL table. The column names are the schema names on the XML. for instance one column of the sql table will be 'Customer type.
Please can you provide me a sql script to do this ?



XML data

XML
<caseresponse xmlns="http://www.aptean.com/respond/caseresponse/2" version="2">
  <case name="kibrom, Ms Karren" id="KibromsData" tag="">
    <field type="Category" schemaname="Case.CustomerType" name="Customer Type">
    <field type="Action" schemaname="Case.LastActionId" name="Last Action">
      <value id="30612">Close
    
    <field type="DateTime" schemaname="Case.OnHoldWarningDate" name="On Hold Warning Date">
      <value>
    
    <field type="Integer" schemaname="Case.WorkingDaysToResolve" name="Working Days To Resolve">
      <value>38
    
    <field type="Integer" schemaname="Case.DerivedElapsedHoursToResolve" name="Derived Elapsed Hours To Resolve">
      <value>1344
    
    <field type="Category" schemaname="Case.ReceivedFrom" name="Received From">
    <field type="DateTime" schemaname="Case.ResolvedDate" name="Resolved Date">
      <value>2023-04-11T15:16:00


EDIT: OP's response to a question - both posted as solutions
I am using Microsoft SQL 2014. Yes i would like to create a table with columns from the XML and store the values.

Transform the XML into SQL table. The column for the SQL table will be the schema name in the XML tag

What I have tried:

Have tried to use
SQL
EXEC sys.sp_xml_preparedocument @idoc OUTPUT, @param_XML

but it didn't work.

I am not sure how can i extract the Schema name to the OpenXML script shown below:
SQL
SELECT text FROM OPENXML (@idoc
Posted
Updated 12-Sep-24 22:29pm
v2
Comments
Kibrom Weldegabriel 3 days ago    
Thanks So much. Its nearly there now. I got the below error. Some of the XMLs doesn't have value for CustomerType. Hence , we need to add a NULL value if the value doesn't exist. Can this be achieved?

Example : <field type="Category" schemaname="Case.CustomerType" name="Customer Type">
<field type="Action" schemaname="Case.LastActionId" name="Last Action">
<value id="30612704ec924645807c828a1aba38a4">Close

Error :
Msg 4121, Level 16, State 1, Line 19
Cannot find either column "CustomerType" or the user-defined function or aggregate "CustomerType.value", or the name is ambiguous.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900