SQL插入表时如何调用函数修改值

问题描述 投票:0回答:1

我的 postgresql 数据库中有一个人员表,其列 id 为 bigserial 类型。我希望每次创建一个新人时,不要为 id 设置一个简单的数字,而是像 YouTube 那样设置一个数字。

为了做到这一点,我创建了一个函数,将 int 转换为复杂的 id,但我不知道如何使用该字符串自动更新 te id。

postgresql function identifier
1个回答
0
投票

您可以尝试这样的方法并调整它以满足您的需求

-- Dummy table to test
CREATE TABLE persons (
  id BIGSERIAL PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE OR REPLACE FUNCTION generate_complex_id() RETURNS TRIGGER AS $$
DECLARE
    hash TEXT;
    result TEXT;
BEGIN
-- Hash will have hexadecimal characters that are hard to convert directly into numeric value
  hash := UPPER(SUBSTRING(string_agg(MD5(CAST(RANDOM() AS TEXT)), ''), 1, 5)) FROM generate_series(1, CAST(CEIL(2/ 32.) AS INTEGER));
-- Wrap the `hash` value such that it can be turned into a numeric value (modify the `int8` to match your desired type)
  EXECUTE 'SELECT x' || quote_literal(hash) || '::int8' INTO result;
-- Concat the date and the converted hash
  NEW.id := CONCAT(TO_CHAR(CURRENT_DATE, 'YYYYMMDD'), result);
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Creating a trigger so that it applies to each insert
CREATE TRIGGER test_trigger BEFORE INSERT ON persons FOR EACH ROW EXECUTE FUNCTION generate_complex_id();

-- Dummy table
INSERT INTO persons (name, email) VALUES ('John Doe', '[email protected]');
INSERT INTO persons (name, email) VALUES ('Johny Doe', '[email protected]');
INSERT INTO persons (name, email) VALUES ('Johne Doe', '[email protected]');
INSERT INTO persons (name, email) VALUES ('Johni Doe', '[email protected]');
INSERT INTO persons (name, email) VALUES ('Johnyee Doe', '[email protected]');
INSERT INTO persons (name, email) VALUES ('Johnlee Doe', '[email protected]');
INSERT INTO persons (name, email) VALUES ('Johnree Doe', '[email protected]');

为了验证这一点

SELECT * FROM persons;

© www.soinside.com 2019 - 2024. All rights reserved.