在函数的select语句中使用Variable

时间:2016-02-04 22:36:54

标签: postgresql

是否可以从已在函数中声明的另一个变量声明变量?

我期待以下的例子..

CREATE OR REPLACE FUNCTION insertRecord
(
    a varchar (100),
    b varchar(100),
    c varchar(100)

) 
RETURNS TEXT AS $$

DECLARE

orgId := (select id from org)

projectId := select id from project where orgId = orgId

BEGIN

return projectId;

END;
$$ LANGUAGE plpgsql;

2 个答案:

答案 0 :(得分:0)

首先声明变量。并重命名orgId以避免与列名称产生歧义。

CREATE OR REPLACE FUNCTION insertRecord 
(
a varchar (100),
b varchar(100),
c varchar(100)

) 
RETURNS TEXT AS $$

DECLARE

orgId_var integer;
projectId varchar;


BEGIN

orgId_var := (select id from org limit 1);

projectId := (select id from project where orgId = orgId_var);

return projectId;

END;
$$ LANGUAGE plpgsql;

答案 1 :(得分:0)

也许您只想使用联接?沿着这些方向的东西(但添加了更多的过滤器以便不返回多行):

CREATE OR REPLACE FUNCTION insertRecord(
    a varchar (100),
    b varchar(100),
    c varchar(100)
)
RETURNS TEXT AS $$

DECLARE

    v_project_id project.id%TYPE;

BEGIN

    SELECT p.id
      INTO v_project_id
      FROM project p
      JOIN org o ON (o.id = p.org_id);

    RETURN v_project_id;

END;
$$ LANGUAGE plpgsql;