仅对支持类型的列执行 LIKE 操作

Performing a LIKE operation only on columns of the supported type

[作业]

我编写了一个 plpgsql 函数,它采用 table 名称作为每一列的输入,其中 table 运行一些涉及 LIKE 运算符的查询。

对于包含类型为 integer 的列的 tables,我得到以下不足为奇的错误:

ERROR: operator does not exist: integer ~~ unknown

这是有道理的,因为 LIKE 对整数类型没有意义。

我可以检查以确保每列的类型不是 integer, date, ... 但是硬编码支持/不支持 LIKE 操作的数据类型似乎很老套,即不是“文本”。此外,数据库中使用了许多自定义数据类型来表示某种字符串。

我想知道解决这个问题的好方法是什么。有没有办法检查某种类型的特定列是否可以支持 LIKE 查询?

不确定是否可以检查类型是否支持 LIKE 运算符,但您始终可以 运行 查询并在错误发生时捕获错误。

在这种情况下,LIKE 运算符会抛出一个 undefined_function 错误。您可以在异常块中捕获此错误并改为执行其他操作。请参阅此示例函数:

CREATE or replace FUNCTION test() RETURNS void AS
$BODY$
BEGIN      
  BEGIN -- begin of the exception block
    PERFORM 1 LIKE '10'; --  <--this code throws a exception
    EXCEPTION
      WHEN undefined_function THEN
        RAISE WARNING '%', 'could not execute query!';
  END;  -- end of the exception block
END;
$BODY$
LANGUAGE plpgsql;

有关详细信息,请参阅 documentation and the list all error codes