6

I try to select values from one xml field and insert selected values to another table field with integer type.

QUERY:

INSERT INTO "Match" 
select 
unnest(xpath('./game/id/text()', "File"))
FROM "Files"

Select works fine, but when I try to insert, then error occurs:

SQL error:
ERROR:  column "id" is of type integer but expression is of type xml
LINE 3: unnest(xpath('./game/id/text()', "File")),

HINT:  You will need to rewrite or cast the expression.

When I try to change xml type with cast, then I get another error:

SQL error:
ERROR:  cannot cast type xml to integer
LINE 3: cast(unnest(xpath('./game/id/text()', "File"))as integer)

And when I try to change type with XMLSERIALIZE, then another error occurs:

SQL error:
ERROR:  argument of XMLSERIALIZE must not return a set
LINE 3: XMLSERIALIZE(CONTENT unnest(xpath('./game/id/text()', "File"...

How can I insert selected values to another table?

1 Answer 1

9

You start by selecting the text in the XML "id" nodes:

xpath('game/id/text()', col1)

This returns an array, which you unnest, resulting in between zero or more rows:

unnest(xpath('game/id/text()', col1))

A cross join lateral allows you to run unnest(xpath(...)) for every row in the table:

cross join lateral
        unnest(xpath('game/id/text()', col1)) xp(id)

Finally, Postgres can't convert XML to a number. You need an intermediate conversion to text:

select  id::text::int
from    YourTable
cross join lateral
        unnest(xpath('game/id/text()', col1)) xp(id)

Example at SQL Fiddle.

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.