Postgresql 将选择查询分配给函数中的变量

Xia*_*lin 4 postgresql variables function

我正在使用 Postgresql 9.3 并编写了一个函数,如下所示:

    create or replace function test(building text,floor text) returns void as $$
    Declare
    id integer;
    num integer := 0;
    Begin

    num=num+100

    id :=select to_number(
          (select 
              (select code from buildings where name=building) || floor 
              || (select num::text)),'99999999'
    );

    update table set col1=id;

    End;
    $$
    language plpgsql;
Run Code Online (Sandbox Code Playgroud)

我想到的是,我的id变量将被分配一个数值example: 12502100select to_number(...)查询。

但是我收到以下错误

ERROR:  syntax error at or near ":="
LINE 10: source :=(select code from buildings where name='I3')
Run Code Online (Sandbox Code Playgroud)

如何将查询结果(带有一些字符串操作)分配到变量 id 中?

我的Select Into id...方法也失败了。

Pav*_*ule 5

您不需要SELECT用于函数评估。

id := to_number((SELECT code FROM buildings WHERE name = building) 
                                                      || floor || num::text,
                '999999999');
Run Code Online (Sandbox Code Playgroud)

另一种可能性(通常更好)是在表达式列表(结果字段列表)中使用函数

id := (SELECT to_number(code || floor || num::text, '99999999') 
          FROM buildings WHERE name = building)
Run Code Online (Sandbox Code Playgroud)

使用SELECT只有当你需要查询数据,而不是函数或变量的评价!