Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare row type variable in PL/pgSQL

Tags:

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 $$; 

Am I right?

If I want to get only 2-3 columns instead of all columns. How can I define my_data?

That is,

DO $$ DECLARE my_data <WHAT HERE??>; BEGIN SELECT id,name,surname FROM t INTO my_data WHERE id = ?; END $$; 
like image 259
Vyacheslav Avatar asked Oct 02 '15 18:10

Vyacheslav


People also ask

How do I declare a record variable in PostgreSQL?

We can declare a record type variable by simply using a variable name followed by the record keyword. Syntax: variable_name record; We can use the dot notation (.) to access any field from the record type variable.

What is record type variable in Pqsql?

Introduction to PL/pgSQL record types A record variable is similar to a row-type variable. It can hold only one row of a result set. Unlike a row-type variable, a record variable does not have a predefined structure.

How do I assign a variable in PostgreSQL?

Variables can be assigned default values within the declaration section of a PL/pgSQL code block. This is known as default value assignment, and is done by using the assignment operator (:=) on the same line as the variable's declaration.

How do I select a row in PostgreSQL?

If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names. The select list may also contain expressions or literal values. Second, specify the name of the table from which you want to query data after the FROM keyword.


1 Answers

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 $$; 
like image 175
Erwin Brandstetter Avatar answered Oct 28 '22 22:10

Erwin Brandstetter