DO$$DECLAREproduct_titleproducts.product_name%TYPE;BEGINSELECTproduct_nameFROMproductsINTOproduct_titlewhereproduct_id=1limit1;RAISENOTICE'Your product name is %',product_title;END;$$
Function Parameter w/t IN and OUT
CREATEORREPLACEFUNCTIONfn_sum_using_inout(INxinteger,INyinteger,OUTZinteger)as$$BEGINz:=x+y;END;$$LANGUAGEPLPGSQL;selectfn_sum_using_inout(2,3);-- another exampleCREATEORREPLACEFUNCTIONfn_sum_using_inouts(INxinteger,INyinteger,OUTZinteger,OUTwinteger)as$$BEGINz:=x+y;w:=x*y;END;$$LANGUAGEPLPGSQL;select*fromfn_sum_using_inouts(2,3);
Nested functions
DO$$<<Parent>>DECLAREcounterinteger:=0;BEGINcounter:=counter+1;RAISENOTICE'the current value of counter (IN PARENT) is %',counter;DECLAREcounterinteger:=0;BEGINcounter:=counter+5;RAISENOTICE'The current value of counter at subblocks is %',counter;RAISENOTICE'The parent value of counter at subblocks is %',PARENT.counter;END;counter:=counter+5;RAISENOTICE'the current value of counter (IN PARENT) is %',counter;END;$$LANGUAGEPLPGSQL;
CREATEORREPLACEFUNCTIONfn_which_is_greater(xintegerdefault0,yintegerdefault0)RETURNStextAS$$BEGINIFx>ythenreturn' x > y ';elsereturn' x < y ';endif;END;$$LANGUAGEPLPGSQL;SELECTfn_which_is_greater(4,3);
DO$$DECLARErecrecord;orderidsmallint=1;BEGINSELECTcustomer_id,order_dateFROMordersINTOSTRICTrecWHEREorder_id=orderid;EXCEPTIONWHENNO_DATA_FOUNDTHENRAISEEXCEPTION'No order id was found';END;$$LANGUAGEPLPGSQL;
Throwing execption on condition
DO$$DECLARErecrecord;orderidsmallint=1;BEGINSELECTcustomer_id,order_dateFROMordersINTOSTRICTrecWHEREorder_id>1000;EXCEPTIONWHENTOO_MANY_ROWSTHENRAISEEXCEPTION'Too many rows were found';END;$$LANGUAGEPLPGSQL;
Throwing execption example
CREATEORREPLACEFUNCTIONfn_div_exception(xreal,yreal)RETURNSrealas$$DECLAREretreal;BEGINret:=x/y;returnret;EXCEPTIONWHENdivision_by_zerothenRAISEINFO'division by zero error';RAISEINFO'ERROR % %',SQLSTATE,SQLERRM;END;$$LANGUAGEPLPGSQL;SELECTfn_div_exception(5,0);