使用plpgsql的`RETURN SETOF`返回一个带连接的简单查询

时间:2016-12-06 21:14:29

标签: postgresql plpgsql

我在postgresql中返回值时遇到麻烦,我创建了这样的函数(EDITED):

CREATE OR REPLACE FUNCTION GetComissionamento(pv varchar(50))
RETURNS SETOF tb_comissionamentos AS
$$
BEGIN
SELECT com.* FROM tb_vendas as vendas 
 INNER JOIN tb_pagamentos as pg on vendas.id_venda = pg.id_venda
 INNER JOIN tb_comissionamentos as com on vendas.id_venda = com.id_venda 
    AND com.id_pagamento = pg.id_pagamento
 WHERE id_venda_imobiliaria = pv;
END
$$
LANGUAGE plpgsql;

我想在表格tb_comissionamento上返回数据,如查询所示。 我该怎么办?当我调用该函数时,我收到了错误消息:

ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.

2 个答案:

答案 0 :(得分:2)

这很糟糕。

  1. 这应该是VIEW而不是功能
  2. 像这样,

    CREATE VIEW GetComissionamento AS 
    SELECT com.* FROM tb_vendas as vendas 
         INNER JOIN tb_pagamentos as pg on vendas.id_venda = pg.id_venda
         INNER JOIN tb_comissionamentos as com on vendas.id_venda = com.id_venda 
            AND com.id_pagamento = pg.id_pagamento;
    

    然后(其中$ pv是你的价值),

    SELECT *
    FROM GetComissionamento
    WHERE id_venda_imobiliaria = $pv; 
    
    1. 如果您打算使用sql而不是plpgsql
    2. 这么简单的话

      像这样,

      CREATE FUNCTION GetComissionamento(varchar(50))
      RETURNS tb_comissionamentos AS $$
      SELECT com.* FROM tb_vendas as vendas 
       INNER JOIN tb_pagamentos as pg on vendas.id_venda = pg.id_venda
       INNER JOIN tb_comissionamentos as com on vendas.id_venda = com.id_venda 
          AND com.id_pagamento = pg.id_pagamento
       WHERE id_venda_imobiliaria = $1;
      $$ LANGUAGE SQL;
      
      1. 如果您打算将其作为plpgsql使用RETURN QUERY
      2. 像这样,

        CREATE OR REPLACE FUNCTION GetComissionamento (pv varchar(50))
        RETURNS tb_comissionamentos AS $$
        BEGIN
          RETURN QUERY
             SELECT com.* FROM tb_vendas as vendas 
             INNER JOIN tb_pagamentos as pg on vendas.id_venda = pg.id_venda
             INNER JOIN tb_comissionamentos as com on vendas.id_venda = com.id_venda 
                AND com.id_pagamento = pg.id_pagamento
             WHERE id_venda_imobiliaria = pv;
          -- error checking or whatever
          RETURN;
        END;
        $$ LANGUAGE plpgsql;
        

答案 1 :(得分:0)

是的,得到了​​错误,忘了返回查询

class UserService { d: UserGroupDao =>
  val dao = d
  def read(userId: String): Future[Option[User]] = dao.readUser(userId)
}

class GroupService { svc: UserService =>
  def createGroup(group: Group): Future[Either[String, String]] = {
    svc.read(group.ownerId) map {
      case Some(_) => svc.dao.createGroup(group)
      case None => Left("Invalid User!")
    }
  }
}