SoFunction
Updated on 2025-04-08

pgsql variable assignment method and precautions

1. The methods generally mentioned on the Internet are as follows:

:=,assignment, such as user_id := 20;

select into assignment, for example

SELECT INTO myrec * FROM emp WHERE empname = myname

2. What I am introducing today is a more general and practical assignment method

select ...into ...

Example of usage:

A variable, select 30 into user_id;

Multiple variables, select 20,30,50 into a,;

3. Into is also commonly used in stored functions (i.e., in stored procedures).

For example, when splicing characters, just enter directly.

select 'update student set remark ='''|| now() ||''' where  = '|| $1 into sql_str_run ;
execute sql_str_run;

Supplement: Postgresql assignment attention

Assigning values ​​in functions requires attention as follows

Defining variables before beginning

Used when assigning variables:=

Use into assigning values ​​in select

as follows:

create or replace...
return i int
declare
value int;
begin
value:=100;
select id into value from table_name
end

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.