Rahmadnet

PL/pgSQL cursors

Jul 30th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. create table student
  2. (
  3.     id integer,
  4.     name varchar(50),
  5.     gender char(1),
  6.     address varchar(100),
  7.     height_student integer,
  8.     weight_student integer
  9. )
  10.  
  11. select * from student
  12.  
  13. insert into student (id, name, gender, address, height_student, weight_student)
  14. values
  15. (2, 'sarah', 'W', 'brazil', 140, 40),
  16. (3, 'reza', 'M', 'england', 155, 55),
  17. (4, 'george', 'M', 'scothland', 160, 60),
  18. (5, 'rani', 'W', 'borneo', 120, 35),
  19. (6, 'raisa', 'W', 'argentina', 146, 46),
  20. (7, 'fahmi', 'M', 'indonesia', 167, 60),
  21. (8, 'kana', 'M', 'hindia', 170, 55),
  22. (9, 'panji', 'M', 'prancis', 180, 67),
  23. (10, 'rambo', 'M', 'belgia', 178, 87);
  24.  
  25. create or replace function get_students_address(p_id integer)
  26.     returns text as $$
  27. declare
  28.     addresss text default '';
  29.     rec_student record;
  30.     cur_student cursor (p_id integer)
  31.     for select name, id
  32.     from student
  33.     where id = p_id;
  34. begin
  35.     --  open the cursor
  36.     open cur_student(p_id);
  37.  
  38.     loop
  39.     --  fetch row into the student
  40.     fetch cur_student into rec_student;
  41.     --  exit when no more row to fetch
  42.     exit when not found;
  43.  
  44.     --build the output
  45.     if rec_student.address like '%' then
  46.         addresss := addresss || ',' || rec_student.address || ':' || rec_student.id;
  47.     end if;
  48. end loop;
  49.  
  50.     --close the cursor
  51.     close cur_student;
  52.    
  53.     return addresss;
  54. end; $$
  55. language plpgsql;
  56.  
  57. select get_students_address(1);
Advertisement
Add Comment
Please, Sign In to add comment