簡體   English   中英

在存儲過程postgres中創建自定義列

[英]Creating Custom columns in stored procedure postgres

我正在使用存儲過程返回在我大學就讀的學生的類型。 推入他們的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 ;

這是多種多樣的倒退。 游標將使用有效的SQL,而不使用plpgsql命令。 但是,您不需要游標或plpgsql。 一個簡單的SQL函數應該執行以下操作:

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);

可以像在FROM列表中的表一樣使用set-turning函數。
字符串文字用單引號引起來!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM