gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:17:06 24 4
gpt4 key购买 nike

我正在尝试使用分类器表中的 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'、'是否为系统使用夏令时'、'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($1 AS ' || 'boolean' || ')'
INTO value
USING 'true';

2) 创建一个包含大量 if 的函数,它返回转换后的值例如IF type = 'boolean' THEN return 'value'::boolean

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

最佳答案

您的解决方案 1) 大部分是正确的。

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

为了保证安全,写:

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

关于sql - 如何在plpgsql中使用变量作为字段类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47573578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com