首页 > 解决方案 > 在插入 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 类型的列,我如何一般地过滤它们的所有列值(不指定列名)?

标签: postgresqlintbigint

解决方案


如果要跟踪,可以执行以下操作:

创建一个这样的函数:

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。


推荐阅读