Postgres使用记录类型功能创建视图

时间:2013-02-23 01:30:39

标签: function postgresql record plpgsql

我有一个复杂的查询,用户定义的函数conta_relatos()作为select语句运行得非常好。但是当我尝试使用相同的指令创建视图时,它不起作用。 Postgres告诉我“conta_relatos”栏目有伪类型记录。此函数conta_relatos()返回记录类型变量 编辑补充:
返回类型是前面提到的一个众所周知的复合类型:
Postgres Function End Loop and return Error

以下是查询:

CREATE OR REPLACE VIEW "Sumario" AS 
SELECT "Aspectos"."ID" AS "Aspecto Normativo ID", 
    "Aspectos"."Aspecto" AS "Aspecto Normativo", 
    "Fatores"."ID" AS "Fator Normativo ID", 
    "Fatores"."Fator" AS "Fator Normativo", "Diagnostico"."Vinculo_Final", 
    "Fatores_1"."ID" AS "Fator Determinativo ID", 
    "Fatores_1"."Fator" AS "Fator Determinativo", 
    "Aspectos_1"."ID" AS "Aspecto Determinativo ID", 
    "Aspectos_1"."Aspecto" AS "Aspecto Determinativo", 
    count("Itens"."ID") AS "No Itens", 
    conta_relatos("Fatores"."ID", "Fatores_1"."ID")
FROM  
    "Diagnostico"
JOIN ("Aspectos" "Aspectos_1"
JOIN ("Fontes"
JOIN "Itens" ON "Fontes"."ID" = "Itens"."Fonte"
JOIN ("Fatores" "Fatores_1"
JOIN ("Aspectos"
JOIN ("Vinculos"
JOIN "Fatores" ON "Vinculos"."Fator_Normativo" = "Fatores"."ID") ON "Aspectos"."ID" = "Fatores"."Aspecto" AND "Aspectos"."ID" = "Fatores"."Aspecto") ON "Fatores_1"."ID" = "Vinculos"."Fator_Determinativo") ON "Itens"."ID" = "Vinculos"."Item") ON "Aspectos_1"."ID" = "Fatores_1"."Aspecto") ON "Diagnostico"."ID" = "Vinculos"."Diagnostico_ID"
GROUP BY "Aspectos"."ID", "Aspectos"."Aspecto", "Fatores"."ID", "Fatores"."Fator", "Diagnostico"."Vinculo_Final", "Fatores_1"."ID", "Fatores_1"."Fator", "Aspectos_1"."ID", "Aspectos_1"."Aspecto"
ORDER BY "Aspectos"."ID", "Aspectos_1"."ID", "Fatores"."Fator", "Fatores_1"."Fator";

1 个答案:

答案 0 :(得分:1)

仔细检查:您只需要拆分复合返回类型,如下所示:

CREATE OR REPLACE VIEW "Sumario" AS 
SELECT ...
 (conta_relatos("Fatores"."ID", "Fatores_1"."ID")).*
FROM ...

Details about accessing composite types in the manual.

顺便说一句:除非你确切知道自己在做什么,否则我建议不要在你的JOIN中使用括号。你拥有它的方式,你正在强迫一个特定的执行计划。机会是,它不是最好的。


第一种方法误解了错误消息

当您使用RETURNS record定义一个函数时(我尽可能避免),您必须为每个调用提供一个列定义列表,如:

SELECT * FROM conta_relatos(1,2) AS f(col1 int, col2 text, ...)

我引用the manual here

  

如果函数已被定义为返回记录数据类型,   然后必须存在别名或关键字AS,后跟一列   表单中的定义列表(column_name data_type [,...])。该   列定义列表必须与实际的数量和类型相匹配   函数返回的列。

干净的解决方案是更改您的函数以返回众所周知的类型而不是匿名记录。根据具体情况,有各种方法可以解决这个问题。如果您在重写功能时遇到问题,请打开另一个问题。