postgresqlfunctionenumsinput-parameters

How to pass ENUM variable as input for POSTGRESQL functions


I have a function in MySQL which works fine:

CREATE  PROCEDURE `Accounts_Active`(IN_DeptName VARCHAR(255), IN_Src ENUM('TRAINING','ELZA'))
BEGIN
END$$
DELIMITER ;

But when converted to PostgreSQL:

CREATE or replace FUNCTION Accounts_Active(IN_DeptName VARCHAR(255), IN_Src ENUM('TRAINING','ELZA'))
RETURNS void
AS
$$
BEGIN
      RAISE INFO '    ';
END;
$$ LANGUAGE plpgsql;

The following error occurs:

ERROR:  type enum does not exist
SQL state: 42704

Any guidance on how I can fix this error would be appreciated.


Solution

  • Create an enum data type:

    CREATE TYPE atype AS ENUM ('TRAINING', 'ELZA');
    

    Then you can use it as function parameter:

    CREATE FUNCTION Accounts_Active(
       IN_DeptName text,
       IN_Src atype
    ) RETURNS void
    ...
    

    When using enums, remember that you can add values to such a data type, but never again remove them. Often you will be better of using a string data type like text, but of course then you have to write code that checks the input for validity.