DROP FUNCTION IF EXISTS public.fn_getehrrus5o5e88vhc6;

CREATE OR REPLACE FUNCTION public.fn_getehrrus5o5e88vhc6(
    code int
)
    RETURNS int
    LANGUAGE plpgsql
AS
$$
DECLARE
    p_code int := code;

BEGIN
    
    IF (LENGTH(p_code::varchar) > 2)
    THEN
        
        SELECT e.code
        INTO p_code
        FROM vclib.t_enums e
        WHERE e.enumid = p_code;
    
    END IF;
    
    RETURN (SELECT e.ehrrusid
            FROM ehr.t_ehr_rus_5o5e88vhc6 e
            WHERE e.is_dul = TRUE
              AND e.codeehr = (CASE
                                   WHEN p_code = 2 THEN '1'
                                   WHEN p_code = 3 THEN '6'
                                   WHEN p_code = 4 THEN '27'
                                   WHEN p_code = 5 THEN '9'
                                   WHEN p_code = 6 THEN '11'
                                   WHEN p_code = 7 THEN '12'
                                   WHEN p_code = 8 THEN '25'
                                   WHEN p_code = 9 THEN NULL
                                   WHEN p_code = 10 THEN NULL
                                   WHEN p_code = 11 THEN NULL
                                   WHEN p_code = 12 THEN '14'
                                   WHEN p_code = 13 THEN '3'
                                   WHEN p_code = 14 THEN '7'
                                   WHEN p_code = 15 THEN '7'
                                   WHEN p_code = 16 THEN '10'
                                   WHEN p_code = 17 THEN '5'
                                   WHEN p_code = 18 THEN '2'
                                   WHEN p_code = 19 THEN '29'
                                   WHEN p_code = 20 THEN NULL
                                   WHEN p_code = 21 THEN '18'
                                   WHEN p_code = 22 THEN '17'
                                   WHEN p_code = 23 THEN '32'
                                   WHEN p_code = 24 THEN '13'
                                   WHEN p_code = 25 THEN NULL
                                   WHEN p_code = 26 THEN '39'
                                   WHEN p_code = 27 THEN NULL
                                   WHEN p_code = 99 THEN NULL
                               END)
            LIMIT 1
           );

END;
$$