我正在嘗試動態生成文本值,在檢查它們的唯一性時將它們插入到表中,然后從函式中回傳這些值。我設法做到了#1 和#2,但我找不到函式回傳生成值的方法。最后一次嘗試是這個。從函式回傳一個表并在 Return 子句中使用的函式體中創建一個臨時表。
CREATE OR REPLACE FUNCTION add_unique_codes(
number_of_codes_to_generate integer,
code_length integer,
effective_date date,
expiry_date date)
RETURNS TABLE(generated_code text)
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
random_code text := '';
BEGIN
CREATE TEMPORARY TABLE generated_codes(cd text) ON COMMIT DROP;
FOR i IN 1..number_of_codes_to_generate LOOP
random_code = unique_random_code(code_length, 'p_codes', 'id');
INSERT INTO p_codes (code, type, effective_date, expiry_date)
VALUES (random_code, 'B', effective_date, expiry_date);
INSERT INTO generated_codes VALUES (random_code);
END LOOP;
RETURN QUERY SELECT cd FROM generated_codes;
END;
$BODY$;
正如我所說,函式 unique_random_code 作業正常,我還看到 p_codes 表中插入了新的“代碼”。唯一的問題是該函式不會回傳一組“代碼”。
謝謝
uj5u.com熱心網友回復:
不需要臨時表或緩慢的 PL/pgSQL FOR 回圈。您可以使用generate_series()來生成行數,以及回傳這些行returning的陳述句選項:INSERT
CREATE OR REPLACE FUNCTION add_unique_codes(
number_of_codes_to_generate integer,
code_length integer,
effective_date date,
expiry_date date)
RETURNS TABLE(generated_code text)
LANGUAGE sql
AS
$BODY$
INSERT INTO p_codes (code, type, effective_date, expiry_date)
select unique_random_code(code_length, 'p_codes', 'id'), 'B', effective_date, expiry_date
from generate_series(1, number_of_codes_to_generate)
returning code;
$BODY$;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/514710.html
