2

SQLServer has a very useful function called OPENXML. It works is used like this:

DECLARE @idoc int
DECLARE @doc varchar(1000)
SET @doc ='
<ROOT>
<Customer CustomerID="VINET" ContactName="Paul Henriot">
   <Order CustomerID="VINET" EmployeeID="5" OrderDate="1996-07-04T00:00:00">
      <OrderDetail OrderID="10248" ProductID="11" Quantity="12"/>
      <OrderDetail OrderID="10248" ProductID="42" Quantity="10"/>
   </Order>
</Customer>
<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">
   <Order CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00">
      <OrderDetail OrderID="10283" ProductID="72" Quantity="3"/>
   </Order>
</Customer>
</ROOT>'
--Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc

-- Execute a SELECT statement that uses the OPENXML rowset provider.
SELECT *
FROM OPENXML (@idoc, '/ROOT/Customer',1)
WITH (CustomerID  varchar(10),
      ContactName varchar(20))

With a result:

CustomerID ContactName          
---------- -------------------- 
VINET      Paul Henriot
LILAS      Carlos Gonzlez

Does someone know of an alternative for Postgres?

0

2 Answers 2

1

This is currently not possible in PostgreSQL (unless someone has written awesome code that he didn't tell anyone about until now).

Sign up to request clarification or add additional context in comments.

Comments

1

I'm sure this code can be improved, but this appears to return the same result in Postgres as the code you posted does in SQL Server.

WITH test_xml(data) AS (VALUES
  ('<ROOT>
    <Customer CustomerID="VINET" ContactName="Paul Henriot">
       <Order CustomerID="VINET" EmployeeID="5" OrderDate="1996-07-04T00:00:00">
          <OrderDetail OrderID="10248" ProductID="11" Quantity="12"/>
          <OrderDetail OrderID="10248" ProductID="42" Quantity="10"/>
       </Order>
    </Customer>
    <Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">
       <Order CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00">
          <OrderDetail OrderID="10283" ProductID="72" Quantity="3"/>
       </Order>
    </Customer>
    </ROOT>'::XML)
)
SELECT  unnest((xpath('//Customer/@CustomerID', test_xml.data))),
        unnest((xpath('//Customer/@ContactName', test_xml.data)))
FROM test_xml

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.