2

Can I declare a function in postgresql which in its input parameter will convert data type of passed parameter. For example:

create or replace function temp(IN var1 integer, IN var2 varchar)
<function body>

select temp('12345','number');

as passed parameter '12345' is a string, I want it to convert directly into integer while passing it to function, something like this:

create or replace function temp(IN var1 ::integer, IN var2 varchar)
    <function body>

Is it possible?

Note: I cannot convert value while passing it to the function like this:

select temp('12345'::integer,'number');

I have to convert it in function definition itself.

2 Answers 2

2

You could create a cast from text to integer, but that's a bad idea as it will lead to surprising behavior somewhere else.

You have two choices:

  • Cast the argument to integer before passing it to the function.

  • Cast the argument to integer inside the function.

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

2 Comments

So, this means I can not perform conversion in function definition itself and I have do it explicitly inside the function?
Right. Type conversion while passing the argument would be an assignment or implicit cast, and I recommend that you do not go that way.
0
CREATE OR REPLACE FUNCTION totalRecords (P1 int, P2 int)
RETURNS integer AS $total$
declare
  total integer;
BEGIN
   total := P1 * P2;
   RETURN total;
END;
$total$ LANGUAGE plpgsql;
select totalRecords('12', 3)
| totalrecords |
| -----------: |
|           36 |

dbfiddle here

You could use CREATE CAST if you need special data type.

CREATE CAST defines a new cast. A cast specifies how to perform a conversion between two data types.

CREATE CAST (source_type AS target_type)
    WITH FUNCTION function_name (argument_type [, ...])
    [ AS ASSIGNMENT | AS IMPLICIT ]

CREATE CAST (source_type AS target_type)
    WITHOUT FUNCTION
    [ AS ASSIGNMENT | AS IMPLICIT ]

CREATE CAST (source_type AS target_type)
    WITH INOUT
    [ AS ASSIGNMENT | AS IMPLICIT ]

1 Comment

I cannot convert it while calling the function, see Note in question.

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.