Advertisement
Rahmadnet

PL/pgSQL function overloading

Jul 24th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. create table new_book
  2. (
  3. id serial,
  4. title text,
  5. author text
  6. );
  7.  
  8. select * from new_book
  9.  
  10. --function untuk mengisi table new_book (ADD)
  11. create or replace function ins_book(p_title varchar, p_author text)
  12. returns integer as
  13. $$
  14. insert into new_book(title, author) values ($1,$2)
  15. returning id;
  16. $$
  17. language 'sql' volatile;
  18.  
  19. select ins_book ('Qowaid Arba', 'Darul Haq') as book_id;
  20. select ins_book ('Aqua', 'Rahad') as new_id;
  21.  
  22. --function untuk mengUpdate new_book (UPDATE)
  23. create or replace function upd_book(log_id integer, p_title text, p_author text)
  24. returns void as
  25. $$
  26. update new_book
  27. set title = $2, author = $3 where id = $1;
  28. $$
  29. language 'sql' volatile;
  30.  
  31. select upd_book(4, 'Aqua', 'Imam');
  32.  
  33. --READ
  34. create or replace function red_book(p_title varchar)
  35. returns table (id int, title text, author text) as
  36. $$
  37. select id, title, author from new_book
  38. where title like $1;
  39. $$
  40. language 'sql' stable;
  41.  
  42. select * from red_book ('sirah nabawi');
  43.  
  44. --OUT
  45. create or replace function red_books_out (p_title varchar, out p_id int, out title text, out p_author text)
  46. returns setof record as
  47. $$
  48. select * from new_book
  49. where title like $1;
  50. $$
  51. language 'sql' stable;
  52.  
  53. select * from red_books_out ('Aqua');
  54.  
  55. --using composite type
  56.  
  57. create or replace function red_book_com(p_title text)
  58. returns setof new_book as
  59. $$
  60. select * from new_book
  61. where title like $1;
  62. $$
  63. language 'sql' stable;
  64.  
  65. select * from red_book_com ('Aqua');
  66.  
  67. --writing
  68. create or replace function red_book_psql()
  69. returns table (id int, title text, author text)as
  70. $$
  71. begin
  72.     return query select * from new_book;
  73. end;
  74. $$
  75. language 'plpgsql' stable;
  76.  
  77. select * from red_book_psql();
  78.  
  79. --trigger function
  80.  
  81. create or replace function f_trig_books() returns trigger as
  82. $$
  83. begin
  84. new.title := upper(new.title);
  85. return new;
  86. end;
  87. $$
  88. language plpgsql volatile;
  89.  
  90. create trigger trigger_books
  91. before insert or update of title, author
  92. on new_book
  93. for each row
  94. execute procedure f_trig_books();
  95.  
  96. select ins_book('bahasa arab', 'darul haq') as new_id;
  97.  
  98. drop function ins_book
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement