【问题标题】:Filter bigint values on insert Postgresql在插入 Postgresql 时过滤 bigint 值
【发布时间】:2020-06-11 06:02:43
【问题描述】:

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

【问题讨论】:

    标签: postgresql int bigint


    【解决方案1】:

    据我所知,没有通用的解决方案。

    但我会写成

    INSERT INTO test_int_table
    SELECT *
    FROM test_table AS t
    WHERE t.id BETWEEN -2147483647 AND 2147483647;
    

    【讨论】:

      【解决方案2】:

      如果你想跟踪,你可以这样做:

      创建一个这样的函数:

      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。

      【讨论】:

        猜你喜欢
        • 2020-06-10
        • 2020-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-05
        • 1970-01-01
        • 1970-01-01
        • 2014-04-08
        相关资源
        最近更新 更多