Re: Strange syntax with select - Mailing list pgsql-general

From Adrian Klaver
Subject Re: Strange syntax with select
Date
Msg-id 567D781E.3040002@aklaver.com
Whole thread Raw
In response to Re: Strange syntax with select  ("Edson F. Lidorio" <edson@openmailbox.org>)
List pgsql-general
On 12/25/2015 08:26 AM, Edson F. Lidorio wrote:
>
>
> On 25-12-2015 13:09, Charles Clavadetscher wrote:
>>
>> Hello
>>
>> I am not in clear what your use case is, but you may have a look at that:
>>
>> http://www.depesz.com/2013/02/25/variables-in-sql-what-how-when/
>>
>> The bottom line is that in a psql interactive session you cannot
>> really set a variable as the result of a select statement (or at least
>> I did not fine a way). Instead, depending on what you actually want to
>> achieve, you may use a workaround storing a statement or part of it in
>> a variable.
>>
>> Here an example:
>>
>> db=> create table test (id int);
>>
>> CREATE TABLE
>>
>> db => insert into test select generate_series(1,10);
>>
>> INSERT 0 10
>>
>> db => \set testvar 'sum(id) from test'
>>
>> db => select :testvar;
>>
>> sum
>>
>> -----
>>
>>  55
>>
>> (1 row)
>>
>> Bye
>>
>> Charles

>> Edson
>>
> via pgadmin not accept this syntax.

That is because \set is unique to the psql interactive client and the
pgAdmin SQL Query tool does not understand it.

> You have any other way to do?

Yes inside a function. I suspect that is where you got this:

"select sum(vlr_saldo_inicial) as saldo_ini
into v_saldo_ini
from contas;"

Someone posted something similar from a plpgsql function. To make things
confusing the above is a way you can assign output into a variable in
plpgsql. For the details see:

http://www.postgresql.org/docs/9.4/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW

in particular:

"Tip: Note that this interpretation of SELECT with INTO is quite
different from PostgreSQL's regular SELECT INTO command, wherein the
INTO target is a newly created table. If you want to create a table from
a SELECT result inside a PL/pgSQL function, use the syntax CREATE TABLE
... AS SELECT."



--
Adrian Klaver
adrian.klaver@aklaver.com


pgsql-general by date:

Previous
From: Adrian Klaver
Date:
Subject: Re: Strange syntax with select
Next
From: Adrian Klaver
Date:
Subject: Re: Strange syntax with select