0

I am trying to convert the following SQL Server query to Postgresql

 select CAST(CAST('<IncludeSettle/><StartTime value="2019-03-26 08:45:48.780"></StartTime>' as XML).value('(//StartTime/@value)[1]', 'datetime') AS varchar(40)) + ''')';

I have tried converting it to below and got back following error.

 select unnest(xpath('//StartTime/@value', xmlparse(document '<IncludeSettle/><StartTime value="2019-03-26 08:45:48.780"></StartTime>')))

Error:

    ERROR:  invalid XML document
    DETAIL:  line 1: Extra content at the end of the document
    <IncludeSettle/><StartTime value="2010-03-26 08:45:48.780"></StartTim
                               ^
    SQL state: 2200M

As a hack, I had made the following change to make it work.

 select unnest(xpath('//StartTime/@value', xmlparse(document '<tempzz>'||'<IncludeSettle/><StartTime value="2019-03-26 08:45:48.780"></StartTime>'||'</tempzz>')))

Output for Postgresql:

 2019-03-26 08:45:48.780

I am looking for a better solution. Any help really appreciated.

3
  • As per the documentation, "The second argument must be a well formed XML document. In particular, it must have a single root node element.". It may be easier to use regex to extract the value you want. Or, do what you're doing, add a root node yourself. I've done exactly that in a few cases in the past where I needed to use xpath but there was no root node. Commented Nov 21, 2019 at 9:53
  • Adding the dummy root seems to be the best solution. Commented Nov 21, 2019 at 10:15
  • OK, how do I convert this output to timestamp type.? Commented Nov 21, 2019 at 10:19

1 Answer 1

1

You can process that by adding the dummy root as you did. The value is already formatted as an ISO timestamp, so you can simply cast it to a timestamp:

But as there is no direct cast from xml to timestamp you need to cast the result of the xpath() to text first.

with data (input) as (
 values ('<IncludeSettle/><StartTime value="2019-03-26 08:45:48.780"></StartTime>')
)
select (xpath('//StartTime/@value', ('<dummy_root>'||input||'</dummy_root>')::xml))[1]::text::timestamp
from data
Sign up to request clarification or add additional context in comments.

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.