问题
I have these two similar queries but in the first case it works Ok but in the second fails
CREATE OR REPLACE FUNCTION XmlNodes(xmlData xml, selector TEXT) RETURNS TABLE(r xml)
AS $$ SELECT unnest(xpath(selector, xmlData)); $$ LANGUAGE SQL;
with tmp (x) AS(
SELECT r from
XmlNodes('<Data>
<RegDeletedItem Id="a60ded3d-2d2f-4f57-91d5-0091579bddb9" />
<RegDeletedItem Id="4295e41c-0a09-4601-984a-eac7a9e91fe1" />
</Data>', '/Data/RegDeletedItem')),
sel (y) AS (
select CAST(unnest(xpath('/RegDeletedItem/@Id', r.x))::varchar AS uuid) AS "DeletedItem_ForeignEntity" from tmp as r)
SELECT COALESCE(y, '00000000-0000-0000-0000-000000000000') AS "DeletedItem_ForeignEntity" from sel
And this fails with
ERROR: set-valued function called in context that cannot accept a set
SELECT coalesce((CAST(unnest(xpath('/RegDeletedItem/@Id', r))::varchar AS uuid)), '00000000-0000-0000-0000-000000000000') AS "DeletedItem_ForeignEntity" from
XmlNodes('<Data>
<RegDeletedItem Id="a60ded3d-2d2f-4f57-91d5-0091579bddb9" />
<RegDeletedItem Id="4295e41c-0a09-4601-984a-eac7a9e91fe1" />
</Data>', '/Data/RegDeletedItem') as r;
Is there any way to make the latter work?
回答1:
Ok, I've found the way, mind the SELECT from xpath:
SELECT coalesce((CAST((SELECT x[1]::varchar FROM xpath('/RegDeletedItem/@Id', r) AS x) AS uuid)), '00000000-0000-0000-0000-000000000000') AS "DeletedItem_ForeignEntity" from
XmlNodes('<Data>
<RegDeletedItem Id="a60ded3d-2d2f-4f57-91d5-0091579bddb9" />
<RegDeletedItem Id="4295e41c-0a09-4601-984a-eac7a9e91fe1" />
</Data>
', '/Data/RegDeletedItem') as r;
来源:https://stackoverflow.com/questions/14826990/postgresql-coalesce-and-set-valued-function-called-in-context-that-cannot-accept