2016-04-25 9 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。 – Zeke

+0

これはあなたのコードで行うことです: 'select fname、lname、" Commuter "from Role' from people'。二重引用符で囲まれた識別子で大文字と小文字が区別されることにご注意ください。 http://stackoverflow.com/a/20880247/939860 –

関連する問題