首页 > 解决方案 > 插入唯一的随机值,没有在 PostgreSQL 中定义的任何约束

问题描述

我想在第一个循环中生成唯一的随机客户 id 值,所以它检查 i 的值是否小于 0.2,如果 i 值 > 0.2,它将 Null 添加到该行,那么它应该添加一个不应该的唯一随机值以前出现在该列中。我不想对此列使用 UNIQUE 或 PK 约束,因为我想向它添加多个 Null 值,这也不是 PK。我需要一个有效的方法。这是我迄今为止所做的事情,但未能实现我想要的。我是 PostgreSQL 新手,所以请帮帮我。谢谢。

CREATE OR REPLACE FUNCTION aa_dev.rand_cust(low INT ,high INT)
  RETURNS TABLE (Cust_id  int) AS
$$
declare

i int := 0;
counter int := 0;
rand int := 0;
begin

    DROP TABLE IF EXISTS aa_dev.Customer;

    CREATE TABLE IF NOT EXISTS aa_dev.Customer (
    Cust_id INT
    );

    while counter <= high loop
        rand = floor(random()* (high-low + 1) + low);
        i = random()* (1-0 + 1) + 0;
        if i > 0.2 then
            Insert into aa_dev.Customer (Cust_id) values(rand);
            IF (EXISTS(SELECT rand_cust.Cust_id FROM aa_dev.Customer WHERE rand_cust.Cust_id = rand)) THEN
                UPDATE aa_dev.Customer SET rand_cust.Cust_id = floor(random()* (high-low +1) + low) WHERE rand_cust.Cust_id = rand;
            END IF;
            -- Insert into aa_dev.Customer (Cust_id) values(floor(random()* (high-low + 1) + low))
        else
            Insert into aa_dev.Customer (Cust_id) values(Null);
        end if;
        counter := counter + 1;
    end loop;

    return query
    select *
    from aa_dev.Customer;
end

$$
LANGUAGE plpgsql;

select * from aa_dev.rand_cust(1, 50);

标签: postgresql

解决方案


推荐阅读