1

I'm trying to handle empty '' values in FUNCTION variable. What should be the correct way to return nothing when calling the function with empty value like below

SELECT *
FROM metadata.fn_get_id('mea', 'sau', '');




DROP FUNCTION IF EXISTS metadata.fn_get_id(VARCHAR, VARCHAR, NUMERIC);

CREATE OR REPLACE FUNCTION metadata.fn_get_id(a1 CHARACTER VARYING, b2 CHARACTER VARYING,
                                                            c3 NUMERIC DEFAULT 0
) RETURNS INT
    LANGUAGE plpgsql
AS
$$
DECLARE
    linked_id INT;
BEGIN
    EXECUTE
            'SELECT linked_id::INT FROM ' || $1 || '_region
                WHERE 1=1 AND iso=upper(' || QUOTE_LITERAL($2) || ') AND id = '|| $3 ||' limit 1;'
        INTO linked_id;
    RETURN linked_id;

END


$$;

-- TEST LINK_ID 1213506417 (PASS)
SELECT *
FROM metadata.fn_get_id('mea', 'sau', 414803422);

-- TEST Null (PASS)
SELECT *
FROM metadata.fn_get_id('mea', 'sau');

-- TEST empty (FAILS ... HOW to Handle)
SELECT *
FROM metadata.fn_get_id('mea', 'sau', '');
1
  • 1
    You can't pass an empty string ('') for a numeric value to begin with. The obvious choice is pass null instead Commented Mar 23, 2022 at 13:26

2 Answers 2

1

Make c3 function argument type text default null and check for empty string first thing in the function body.

create or replace function metadata.fn_get_id(a1 text, b2 text, c3 text default null)
RETURNS integer language plpgsql as
$$
declare 
 -- your declarations
begin
    if nullif(c3, '') is null then
        return null;
    end if;
 -- your function body
$$;

Call:

SELECT *
FROM metadata.fn_get_id('mea', 'sau', 414803422::text);

Btw the function in the example is injection prone.

Sign up to request clarification or add additional context in comments.

4 Comments

There is no need to define the parameter as text - numeric can handle NULL values just as well.
Sure, but what about an empty string as the OP says?
He shouldn't pass an empty string for a numeric parameter to begin with. That's exactly what null is for.
No, he shouldn't. Yet strange enough this is exactly what he is asking about. I do agree however that it is very wrong to encourage bad practices.
0

Simply call the function like this:

metadata.fn_get_id('mea', 'sau', nullif('', ''))

So that an empty string is replaced with NULL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.