4

I have the following table:

Example:

create table test
( 
 id int,
 name varchar(10),
 city varchar(10)
);

I want to assign ID value from table to variable in the function.

Function:

create or replace function testing(ids int,names varchar(10),citys varchar(10)
returns void as
$body$
Declare
       ident int;
BEGIN
       ident := SELECT ID FROM test;
       raise info '%',ident;
END;
$body$
Language plpgsql;

Error Details:

ERROR:  syntax error at or near "SELECT"
LINE 12:  ident := SELECT ID from test;

1 Answer 1

13

Use select ... into

create or replace function testing(ids int,names varchar(10),citys varchar(10)
returns void as
$body$
Declare
       ident int;
       foo   text;
BEGIN
       SELECT ID, some_col  
          into ident, foo 
       FROM test;
       raise info '%',ident;
END;
$body$
Language plpgsql;

More details and examples are in the manual:
http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW

Sign up to request clarification or add additional context in comments.

2 Comments

What if I want to assign multiple values to multiple variables?
As stated in the manual: "where target can be a record variable, a row variable, or a comma-separated list of simple variables and record/row fields" See my edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.