Declare row type variable in PL/pgSQL

后端 未结 1 875
死守一世寂寞
死守一世寂寞 2020-12-30 00:33

As I found SELECT * FROM t INTO my_data; works only if:

DO $$
DECLARE
my_data t%ROWTYPE;
BEGIN
SELECT * FROM t INTO my_data WHERE id = ?;
END $$         


        
相关标签:
1条回答
  • 2020-12-30 01:17

    get only 2-3 columns instead of all columns

    One way: use a record variable:

    DO $$
    DECLARE
       _rec record;
    BEGIN
    SELECT INTO _rec
                id, name, surname FROM t WHERE id = ?;
    END $$;
    

    Note that the structure of a record type is undefined until assigned. So you cannot reference columns (fields) before you do that.

    Another way: assign multiple scalar variables:

    DO $$
    DECLARE
       _id int;
       _name text;
       _surname text;
    BEGIN
    SELECT INTO _id, _name, _surname
                 id,  name,  surname FROM t WHERE id = ?;
    END $$;
    

    As for your first example: %ROWTYPE is just noise in Postgres. The documentation:

    (Since every table has an associated composite type of the same name, it actually does not matter in PostgreSQL whether you write %ROWTYPE or not. But the form with %ROWTYPE is more portable.)

    So:

    DO $$
    DECLARE
       my_data t;  -- table name serves as type name, too. 
    BEGIN
       SELECT INTO my_data  * FROM t WHERE id = ?;
    END $$;
    
    0 讨论(0)
提交回复
热议问题