'Using Switch Case or IF...ELSE Statement in a Dynamic Function Query

Suppose I have a PostgreSQL function that take inputs and inserts them dynamically into a query:

CREATE OR REPLACE FUNCTION cnms_fy22q2.dynamic_function(
    fyq text)
    RETURNS void
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE 
AS $BODY$
BEGIN
    EXECUTE 'SELECT
       region,
       state,
       || fyq || as fisc_quarter,
       CASE
            WHEN RIGHT(fisc_quarter, 1) = '1'
                THEN 'A'
            WHEN RIGHT(fisc_quarter, 1) = '2'
                THEN 'B'
            WHEN RIGHT(fisc_quarter, 1) = '3'
                THEN 'C'
            WHEN RIGHT(fisc_quarter, 1) = '4'
                THEN 'D'
            END
       AS code
    FROM schema_' || fyq || '.my_table';
END
$BODY$;

The above does not work because fisc_quarter is not recognized in the query at this point. I am not sure if I could use the input value fyq perhaps in an IF ELSE statement to replace the Switch Case part. Perhaps first adding:

....
DECLARE
    var1 varchar := ''; 

And then

AS $BODY$
BEGIN 
   IF RIGHT(fisc_quarter, 1) = '1'
       var1 = 'A'
   ELSE IF RIGHT(fisc_quarter, 1) = '2'
       var1 = 'B'
   ELSE IF RIGHT(fisc_quarter, 1) = '3'
       var1 = 'C'
   ELSE IF RIGHT(fisc_quarter, 1) = '4'
       var1 = 'D'

What would be the most appropriate way to set the code column based on the input parameter here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source