Search Postgresql Archives

Re: PL/pgSQL doesn't support variables in queries?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



> On 03/05/2023 14:25 CEST J.A. <postgresql@xxxxxxxxxxxxxxxxxxxxxxx> wrote:
>
> ms-sql person here migrating over to pgsql. One of the first thing's I noticed
> with pgsql (or more specifically, PL/pgSQL) is that it doesn't support
> "variables" in a query?
>
> for example, here's some T-SQL:
>
> DECLARE @fkId INTEGER
>
> SELECT @fkId = fkId FROM SomeTable WHERE id = 1
>
> -- and then do something with that value..
>
> SELECT * FROM AnotherTable WHERE Id = @fkId
> SELECT * FROM YetAnotherTable WHERE FKId = @fkId
> -- etc..

plpgsql does support variable declarations [0] but does not use any special
notation like T-SQL.  An equivalent to your example would be:

	DO $$
	DECLARE
	  v_fkid int;
	  v_rec record;
	BEGIN
	  SELECT fkid INTO v_fkid FROM SomeTable WHERE id = 1;
	  SELECT * INTO v_rec FROM AnotherTable WHERE Id = v_fkid;
	  -- Do something with v_rec ...
	END $$;

Prefixing variable names with v_ is just a convention to avoid ambiguous column
references (assuming that column names are not prefixed with v_) [1].

[0] https://www.postgresql.org/docs/current/plpgsql-declarations.html
[1] https://www.postgresql.org/docs/current/plpgsql-implementation.html#PLPGSQL-VAR-SUBST

--
Erik






[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]

  Powered by Linux