postgresql - 在插入 Postgresql 时过滤 bigint 值
问题描述
我在 Postgresql 中有 2 个具有相同架构的表,唯一的区别是其中一个表 id 字段是 bigint 类型。我需要用数据填充的表的架构如下所示:
create table test_int_table(
id int,
description text,
hash_code int
);
我需要将带有 bigint id 的 test_table 中的数据复制到 public.test_int_table。并且应该过滤掉一些大于 id 范围的值。如何在不对范围进行硬编码的情况下跟踪这些值?我可以做这样的事情,但我想构建更通用的解决方案:
insert into test_int_table
select * from test_table as test
where test.id not between 2147483647 and 9223372036854775808
泛型是指对列名及其数量没有限制。因此,以防万一,我在其他表中有多个 bigint 类型的列,我如何一般地过滤它们的所有列值(不指定列名)?
解决方案
如果要跟踪,可以执行以下操作:
创建一个这样的函数:
CREATE OR REPLACE FUNCTION convert_to_integer(v_input bigint)
RETURNS INTEGER AS $$
DECLARE v_int_value INTEGER DEFAULT NULL;
BEGIN
BEGIN
v_int_value := v_input::INTEGER;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'Invalid integer value: "%". Returning NULL.', v_input;
RETURN NULL;
END;
RETURN v_int_value;
END;
$$ LANGUAGE plpgsql;
并写一个这样的查询:
INSERT INTO test_int_table SELECT * FROM test_table AS t WHERE convert_to_integer(t.id) is not null;
或者您可以修改函数以返回 0。
推荐阅读
- javascript - 获取'未捕获的类型错误:无法读取未定义的属性'帮助者''
- regex - 如何从彭博导入价格?
- javascript - 仅调用一次时,函数被执行两次
- python - os.startfile() 没有打开 .docx 文件
- android - RelativeLayout 有效,而 ConstraintLayout 失败
- tvos - tvOS 13 上的画中画
- masstransit - 使用 MQTT 传输的 MassTransit
- python-3.x - python for循环删除列表中重复的输出数据
- javascript - Docusign 登录过程完成后如何重定向到 iframe
- netlogo - Netlogo 不允许多次链接相同的代理,有什么替代方法?