在存储过程postgres中创建自定义列

时间:2016-04-25 00:15:08

标签: sql database postgresql stored-procedures plpgsql

我正在使用存储过程来返回在我的大学注册的学生类型。推送他们的ID应该在一个新的列中返回他们的名字和姓氏(例如:通勤者,雇员,居民)。我一直收到错误:

ERROR:  syntax error at or near "if"
LINE 8:     if exists (select count(commuterid) > 0 from commuter wh...).

任何提示或想法?

create or replace function roleAtMarist(int, REFCURSOR) returns refcursor as
$$
declare
   identifier      int := $1;
   resultset refcursor := $2;
 begin
  open resultset for
    if exists (select count(commuterid) > 0 from commuter where commuterid = identifier) then
      select fname, lname, "Commuter" as Role
      from people 
      where peopleid = identifier;
    end if;

    if exists (select count(employeeid) > 0 from employee where emplpoyeeid = identifier) then
      select fname, lname, "Employee" as Role
      from people 
      where peopleid = identifier;
    end if;

    if exists (select count(residentid) > 0 from studentpark where residentid = identifier) then
      select fname, lname, "Resident" as Role
      from people 
      where peopleid = identifier;
    end if;
return resultset;
end; 
$$
language plpgsql; 
select roleAtMarist(12, 'resultset') ;
fetch all from results ;

1 个答案:

答案 0 :(得分:0)

这是以多种方式倒退的。游标将使用有效的SQL而不使用plpgsql命令。但是你不需要游标,也不需要plpgsql。一个简单的SQL函数应该:

number

呼叫:

CREATE OR REPLACE FUNCTION role_at_marist(_identifier int)
  RETURNS TABLE (fname text, lname text, "role" text) AS
$func$
   SELECT p.fname, p.lname, text 'Commuter'
   FROM   people 
   WHERE  p.peopleid = $1
   AND    EXISTS (SELECT 1 FROM commuter c WHERE c.commuterid = p.peopleid)

   UNION ALL
   SELECT p.fname, p.lname, 'Employee'
   FROM   people 
   WHERE  p.peopleid = $1
   AND    EXISTS (SELECT 1 FROM employee e WHERE e.emplpoyeeid = p.peopleid)

   UNION ALL
   SELECT p.fname, p.lname, 'Resident'
   FROM   people 
   WHERE  p.peopleid = $1
   AND    EXISTS (SELECT 1 FROM studentpark s WHERE s.residentid = p.peopleid)
$func$ LANGUAGE sql; 

设置返回函数可以像SELECT * FROM role_at_marist(12); 列表中的表一样使用 字符串文字用单引号括起来!