Postgresql coalesce and set-valued function called in context that cannot accept a set

微笑、不失礼 提交于 2019-12-24 08:43:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!