Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i set a value in declared variable p_emp_id to get max emp_id from employee table

as select max_id into a declared variable but not getting a result set of select statement

What I have tried:

SQL
CREATE OR REPLACE FUNCTION public.max_emp_id_select(
    
    )
  RETURNS TABLE(p_emp_id integer) AS
$BODY$

declare p_emp_id integer;
BEGIN
   RETURN QUERY 


select (COALESCE(max(new_emp_id),0) + 1) into p_emp_id
from Employee


select p_emp_id //here not getting variable value
end

END;

$BODY$
  LANGUAGE plpgsql VOLATILE
Posted
Updated 3-Apr-18 8:36am
v3

1 solution

Not sure if I understand the question correctly but should you return only a single value. Something like

SQL
CREATE OR REPLACE FUNCTION max_emp_id_select() RETURNS integer AS 
$BODY$
DECLARE
   p_emp_id integer;
BEGIN
   SELECT COALESCE(max(emp_id),0)
   INTO p_emp_id
   FROM Employee;

   RETURN p_emp_id + 1;
END;
$BODY$ 
LANGUAGE plpgsql;


Sorry for any typos. It's been years since I last used pgplsql...

ADDED
------
Have a try with
SQL
UPDATE employee1 
SET emp_id = max_emp_id_select()
WHERE ...
 
Share this answer
 
v2
Comments
Member 13140552 2-Apr-18 8:58am    
this is something right but we want this variable value to nested query like getting max number and update another table to this variable value
Wendelius 2-Apr-18 10:16am    
Can you post an example how you're going to use this function?
Member 13140552 3-Apr-18 6:01am    
SELECT COALESCE(max(emp_id),0)
INTO p_emp_id
FROM Employee;
update employee1 set emp_id = p_emp_id //here variable p_emp_id cannot access to update emp_id and also not working into p_emp_id
Wendelius 3-Apr-18 14:34pm    
Not sure if I understand your comment correctly, but can you use the function in the statement? See the updated example.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900