Oto Shavadze
Oto Shavadze

Reputation: 42853

Set a value to a variable based on the results of a query (in PL/pgSQL style)

What I need to do is set a value to a variable using the EXECUTING query.

In pure SQL style, I could do something like the following:

// here declaring function and etc...
DECLARE cnt INTEGER;

EXECUTE 'SELECT COUNT(*) FROM t' INTO cnt;

How to achieve the same functionality in the form of a PL/pgSQL function? What is the correct syntax for the following pseudo-code? (The following is obviously the wrong syntax)

cnt :=  EXECUTE ( 'SELECT COUNT(*) FROM t' )   ;

Upvotes: 4

Views: 45122

Answers (3)

Roberto
Roberto

Reputation: 809

you can use SELECT INTO

DECLARE cnt INTEGER;
SELECT INTO cnt count(*) FROM t;

Upvotes: 10

Kurt Burns
Kurt Burns

Reputation: 211

I think what you are looking for is:

cnt := COUNT(*) FROM t;

Upvotes: 21

user80168
user80168

Reputation:

Not sure what you mean by "plpgsql style". The syntax you showed is perfectly OK, as shown in documentation.

Upvotes: 5

Related Questions