Store query result in a variable using in PL/pgSQL

前端 未结 5 1362
别那么骄傲
别那么骄傲 2020-11-29 21:12

How to assign the result of a query to a variable in PL/pgSQL, the procedural language of PostgreSQL?

I have a function:

CREATE OR REPLACE FUNCTION t         


        
5条回答
  •  半阙折子戏
    2020-11-29 21:52

    As long as you are assigning a single variable, you can also use plain assignment in a plpgsql function:

    name := (SELECT t.name from test_table t where t.id = x);
    

    Or use SELECT INTO like @mu already provided.

    This works, too:

    name := t.name from test_table t where t.id = x;
    

    But better use one of the first two, clearer methods, as @Pavel commented.

    I shortened the syntax with a table alias additionally.
    Update: I removed my code example and suggest to use IF EXISTS() instead like provided by @Pavel.

提交回复
热议问题