gpt4 book ai didi

postgresql - 如何测试给定的文本列是否是有效的 oid

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

在 PL/pgSQL 中,我有一个可能包含也可能不包含 oid 的列。我需要检测它是否存在。

目前我是这样做的:

  select oidtext from t into x where name = fname;
if found then
begin
select x::oid into looid;
exception
when SQLSTATE '22P02' then -- invalid oid
null;

但这感觉有点hacky。是否有正面测试,即“此文本列是否为有效的 x 类型”或“这是有效的转换”?

最佳答案

似乎唯一的方法就是捕获异常,但您可以像这样在一个方便的函数中做到这一点:

create or replace function oid_or_null(text)
returns oid language plpgsql immutable as $$
begin
return $1::oid;
exception when invalid_text_representation then
return null;
end $$;

select oid_or_null('123'), oid_or_null('abc');

oid_or_null | oid_or_null
-------------+-------------
123 |
(1 row)

您可以创建一个更通用的 bool 函数:

create or replace function is_valid_cast(text, text)
returns boolean language plpgsql immutable as $$
begin
execute format('select %L::%I', $1, $2);
return true;
exception when others then
return false;
end $$;

select
is_valid_cast('123', 'oid') as oid, is_valid_cast('abc', 'oid') as not_oid,
is_valid_cast('2018-10-10', 'date') as date, is_valid_cast('2018-20-20', 'date') as not_date;

oid | not_oid | date | not_date
-----+---------+------+----------
t | f | t | f
(1 row)

关于postgresql - 如何测试给定的文本列是否是有效的 oid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53622835/

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