I am working on a compatibility issue, I want to create a SQL function which can return an int or a Varchar based on the conditions in the program.
For example, I have a function named foo.
CREATE or REPLACE FUNCTION foo(param VARCHAR(100))
-- Which datatype I should use here?
RETURNS SOME_DATATYPE AS
$$
SELECT
CASE UPPER(param)
WHEN 'varchar' THEN CAST((SELECT 'varchar_value') AS varchar)
WHEN 'int' THEN CAST((SELECT 1426598) AS int)
ELSE param||' is not supported.'
END
$$
LANGUAGE SQL;
For the following queries, I am expecting output as follows.
select pg_typeof(foo('varchar')) from dual;
--I am expecting varchar as output.
select pg_typeof(foo('int')) from dual;
--I am expecting int as output.
Please suggest if such a feature is there, Or any alternative I can try to achieve the same.
WHENparts of such an expression must return the same data type, so that part will already not work. But "can return an int or a Varchar based on the conditions in the program" is also not possible.CAST((SELECT 1426598) AS int)can be simplified toCAST(1426598 AS int)the SELECT is completely useless