2016-04-25 39 views
0

我正在使用存儲過程來返回在我的大學註冊的學生類型。推送他們的ID應該返回他們的名字和姓氏在一個新的列將要作出(例如:通勤者,僱員,居民)。我一直收到錯誤:在存儲過程中創建自定義列postgres

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 ; 

回答

0

這是倒退的多種方式。遊標將使用有效的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清單表。
字符串文字用單引號括起來!

+0

我運行該代碼並收到錯誤:列「通勤者」不存在。 – Zeke

+0

此專欄不在人員中,但我瞭解您嘗試從... role_at_marist訪問它的位置。 – Zeke

+0

@Zeke。這就是你在你的代碼中做的事情:'select fname,lname,「Commuter」作爲來自人的角色。我假設你知道雙引號標識符區分大小寫? http://stackoverflow.com/a/20880247/939860 –