【问题标题】:How to cast string value to enum如何将字符串值转换为枚举
【发布时间】:2013-09-05 08:52:23
【问题描述】:

我有一个带有enum 类型的表,我创建了一个函数来向该表添加数据。我希望该函数能够慷慨地接受什么,因此我将 text 作为枚举类型并希望稍后再转换它。

这是枚举:

CREATE TYPE public.enum_log_priority AS ENUM (
    'critical','error','warning','notice','debug'
);

这是函数:

CREATE OR REPLACE FUNCTION public.log_write(
    _message text,
    _priority text
) RETURNS integer AS
$body$
BEGIN
    _priority = lower(_priority);
    INSERT INTO log (message, priority) VALUES (_message, _priority);

    RETURN 0;
END
$body$
LANGUAGE 'plpgsql';

我知道这行不通:

错误:列“优先级”是 enum_log_priority 类型,但表达式是文本类型

但是我该怎么做呢?

【问题讨论】:

  • 请用所有可能的值指定 enum_log_priority 的结构

标签: postgresql casting enums


【解决方案1】:

【讨论】:

    【解决方案2】:

    像这样改变你的功能:

    CREATE OR REPLACE FUNCTION public.log_write(
        _message text,
        _priority text
    ) RETURNS integer AS
    $body$
    BEGIN
        _priority = lower(_priority);
        INSERT INTO log (message, priority) VALUES (_message, _priority::enum_log_priority);
    
        RETURN 0;
    END
    $body$
    LANGUAGE 'plpgsql';
    

    | sql fiddle demo |

    【讨论】:

      【解决方案3】:

      Postgres 也支持强制转换功能:

      cast(priority AS enum_log_priority);
      

      【讨论】:

        猜你喜欢
        • 2016-07-30
        • 1970-01-01
        • 1970-01-01
        • 2018-11-09
        • 2010-10-03
        • 1970-01-01
        • 2014-09-27
        相关资源
        最近更新 更多