Declare row type variable in PL/pgSQL

走远了吗. 提交于 2019-11-30 08:40:19

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 $$;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!