Tuesday, August 8, 2023

.::: PostgreSQL EDB : Create Store Procedure Simple Calculator :::.

 
1. Create simple calculator
CREATE OR REPLACE FUNCTION Sp_SimpleCalculator(
    num1 NUMERIC,
    num2 NUMERIC,
    operator CHAR(1)
) RETURNS NUMERIC AS $$
BEGIN
    CASE
        WHEN operator = '+' THEN RETURN num1 + num2;
        WHEN operator = '-' THEN RETURN num1 - num2;
        WHEN operator = '*' THEN RETURN num1 * num2;
        WHEN operator = '/' THEN RETURN num1 / num2;
        ELSE RETURN NULL;
    END CASE;
END;
$$ LANGUAGE plpgsql;


2. test execute

select Sp_SimpleCalculator(100,20,'+');
select Sp_SimpleCalculator(100,20,'-');
select Sp_SimpleCalculator(100,400,'-');
select Sp_SimpleCalculator(100,400,'*');
select Sp_SimpleCalculator(100,400,'/');
 


3. check store procedure

SELECT
    n.nspname AS schema_name,
    p.proname AS function_name,
    pg_get_function_arguments(p.oid) AS arguments,
    p.prosrc AS definition
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
where p.proname ilike '%calculator%';
 


4. drop if want to drop

DROP FUNCTION IF EXISTS Sp_SimpleCalculator;

teguhth=# DROP FUNCTION IF EXISTS Sp_SimpleCalculator;
DROP FUNCTION
teguhth=#

No comments:

Post a Comment

Popular Posts