sqlpostgresqlsql-functionselect-into

PostgreSQL save table columns results into variables


I have this function:

DECLARE 
    _first_name text;
    _last_name  text;
BEGIN
SELECT 
    emp.first_name INTO _first_name,
    emp.last_name INTO _last_name,
FROM employee emp LIMIT 1
END;

(I simplified the function to eliminate the information noise)

As you can see, i can get only 1 result because of 'LIMIT'. So i need to store this 2 columns into my 2 variables. But i am getting an error like 'INTO specified more than once'. How to bypass this, any ideas?


Solution

  • Use INTO once as follows:

    SELECT 
        emp.first_name, emp.last_name INTO _first_name, _last_name
    FROM employee emp LIMIT 1
    

    Columns and variables must be in the same sequence respectively.