I've got quite heavy query with FOR
loop to rewrite and would like to do it simpler, using more SQL instead of plpgsql constructions. The query looks like:
FOR big_xml IN SELECT unnest(xpath('//TAG1', my_xml)) LOOP
str_xml = unnest(xpath('/TAG2/TYPE/text()', big_xml));
FOR single_xml IN SELECT unnest(xpath('/TAG2/single', big_xml)) LOOP
CASE str_xml::INT
WHEN 1
THEN
INSERT INTO tab1(id, xml) VALUES (1, single_xml);
WHEN 2
THEN
INSERT INTO tab2(id, xml) VALUES (1, single_xml);
WHEN 3
[...]
WHEN 11
[...]
ELSE
RAISE EXCEPTION 'something'
END CASE;
END LOOP;
END LOOP;
RETURN xmlelement(NAME "out", xmlforest(1 AS out));
I've started to rewrite it for better performance with:
INSERT INTO tab1(id, xml)
SELECT 1, unnest(xpath('/TAG2/single', (SELECT unnest(xpath('//TAG1', my_xml))));
But I'm not sure how to deal with those CASE ... INSERT
statements.
Any ideas?
Or maybe my approach is completely wrong?
edited 25.02.14: PostgreSQL 9.3.1