如何在plpgsql中使用变量作为字段类型?

如何在plpgsql中使用变量作为字段类型?,sql,postgresql,plpgsql,Sql,Postgresql,Plpgsql,我试图使用classificator表中的lookup_类型值将值转换为适当的类型 Table "public.classificator" Column | Type | Collation | Nullable | Default ------------------+--------+-----------+----------+

我试图使用classificator表中的lookup_类型值将值转换为适当的类型

                                 Table "public.classificator"
      Column      |  Type  | Collation | Nullable |                  Default                  
------------------+--------+-----------+----------+-------------------------------------------
 classificator_id | bigint |           | not null | nextval('classificator_id_seq'::regclass)
 classificator    | text   |           | not null | 
 lookup           | text   |           | not null | 
 description      | text   |           |          | 
 lookup_value     | text   |           |          | 
 lookup_type      | text   |           |          | 
例如,我会使用值(“系统设置”、“夏令时设置”、“启用”、“是否对系统使用夏令时”、“true”、“boolean”)

使用变量作为类型时遇到问题

psql测试:

select cast('1' as integer); --> OK

select cast('1' as 'integer');
ERROR:  syntax error at or near "'integer'"
当我尝试在plpgsql中执行此操作时,我有两个选项,如何解决此问题:

(一)

2) 创建一个包含大量ifs的函数,该函数返回铸造值 e、 g.
如果type='boolean',则返回'value'::boolean

这个问题有没有更优雅的解决方案?

你的解决方案1)基本上是正确的

我不认为有一个优雅的解决方案

要使其安全,请编写:

EXECUTE format('SELECT CAST($1 AS %I)', 'bool')
   INTO value                                                              
   USING 'true';

再想一想,函数是不可行的,因为它必须有特定的返回类型:)对其他回答者来说:不要走“也许你可以有一个返回记录的函数…”的路线-我花了一段时间来处理这个问题,然后才想起在使用这些函数的输出时,您必须指定强制转换。我简要地研究了anyelement的类型变形函数,但我必须将第二个元素作为regtype提供,我无法使用变量()生成第二个元素,因此这是另一个死胡同。Pg似乎不喜欢格式的常规类型。我必须将boolean改为bool,smallint改为int2,然后格式就可以了。
EXECUTE format('SELECT CAST($1 AS %I)', 'bool')
   INTO value                                                              
   USING 'true';