如何在plpgsql中使用变量作为字段类型?
How to use variable as field type in plpgsql?
我正在尝试使用来自分类器 table 的 lookup_type 值将值转换为适当的类型。
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 | | |
我会使用示例值 ('SYSTEM_SETTINGS'、'daylight_saving_enabled'、'Use daylight saving for system or not'、'true'、'boolean')。
我在使用变量作为类型时遇到问题。
psql 测试:
select cast('1' as integer); --> OK
select cast('1' as 'integer');
ERROR: syntax error at or near "'integer'"
当我尝试在 plpgsql 中执行此操作时,我有 2 个选项,如何解决此问题:
1)
EXECUTE 'SELECT CAST( AS ' || 'boolean' || ')'
INTO value
USING 'true';
2) 创建一个包含大量 if 的函数,returns 转换值
例如IF type = 'boolean' THEN return 'value'::boolean
等
这个问题有没有更优雅的解决方案?
您的解决方案 1) 大部分是正确的。
我不认为有一个优雅的解决方案。
为了确保安全,请写:
EXECUTE format('SELECT CAST( AS %I)', 'bool')
INTO value
USING 'true';
我正在尝试使用来自分类器 table 的 lookup_type 值将值转换为适当的类型。
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 | | |
我会使用示例值 ('SYSTEM_SETTINGS'、'daylight_saving_enabled'、'Use daylight saving for system or not'、'true'、'boolean')。
我在使用变量作为类型时遇到问题。
psql 测试:
select cast('1' as integer); --> OK
select cast('1' as 'integer');
ERROR: syntax error at or near "'integer'"
当我尝试在 plpgsql 中执行此操作时,我有 2 个选项,如何解决此问题:
1)
EXECUTE 'SELECT CAST( AS ' || 'boolean' || ')'
INTO value
USING 'true';
2) 创建一个包含大量 if 的函数,returns 转换值
例如IF type = 'boolean' THEN return 'value'::boolean
等
这个问题有没有更优雅的解决方案?
您的解决方案 1) 大部分是正确的。
我不认为有一个优雅的解决方案。
为了确保安全,请写:
EXECUTE format('SELECT CAST( AS %I)', 'bool')
INTO value
USING 'true';