2

Postgres table with name postgrestable:

ID    NAME    HTML
1     FRONT   <map> 
              <entry> test </entry>
              </map>

How can i create a update query that appends a new <entry></entry> between the <map> tags. The table should be updated to this form:

ID    NAME    HTML
1     FRONT   <map> 
              <entry> test </entry>
              <entry> secondentry </entry>
              </map>

I have tried with REGEXP_REPLACE between tags, but that deletes all entries between <map> tags and inserts the entry you updated. Any other idea?

2
  • Your map tag is not closed at the end. Is this right? Commented Oct 31, 2018 at 14:47
  • Yes it was a typo, is edited now. Commented Oct 31, 2018 at 14:49

1 Answer 1

1

demo: db<>fiddle

SELECT 
     regexp_replace(xml, match, match || '<entry>secondentry</entry>')
FROM (
    SELECT
        xml,
        (regexp_matches(xml,'^<map>(.*)</map>$'))[1] as match
    FROM (
        SELECT '<map><entry>test</entry></map>' as xml
    ) s
) s

Using your way with regexp_replace:

  1. regexp_matches gives the whole content of <map>
  2. regexp_replace replaces the whole content of <map> with its content AND the new one.

Edit: The whole UPDATE would look like:

UPDATE postgrestable
SET html =
(
    SELECT 
        regexp_replace(xml, match, match || '<entry>secondentry</entry>')
    FROM (
        SELECT
            xml,
            (regexp_matches(xml,'^<map>(.*)</map>$'))[1] as match
        FROM (
            SELECT '<map><entry>test</entry></map>' as xml
        ) s
    ) s
);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much for the effort. It is not meant to be done only by regexp_replace. As i am not experienced with postgres, how can the update query look like with this statement, as i could not make it use.
Updated fiddle and added the UPDATE code. Is this what you are looking for?
I was trying to make it use but unfortunately could not, receive a error : failed to find conversion function from unknown to text. I tried a way now, as following : update postgrestable set html = regexp_replace(html,'</map>', '<entry>secondentry</entry>\1') where id=1; and worked!!! Thank you for the ffort once more!

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.