根据我在PostgreSQL(9.3)How to check a sequence efficiently for used and unused values in PostgreSQL中的上一个问题,我现在有一个table chart_gap,其中包含表格图表中所有未使用的图表编号的列表:
CREATE TABLE chart_gap (chart_number integer);
在尝试更多地理解触发器时,我添加了以下触发器程序或多或少地从该问题中采取:
CREATE OR REPLACE FUNCTION next_chart() RETURNS trigger AS $BODY$
BEGIN
-- Check for empty chart number
IF NEW.chart_number IS NULL THEN
WITH ins AS (
SELECT chart_number
FROM chart_gap
WHERE pg_try_advisory_xact_lock(chart_number)
LIMIT 1
)
DELETE FROM chart_gap c
USING ins i
WHERE i.chart_number = c.chart_number;
NEW.chart_number := select chart_number from ins; <--WRONG!
END IF;
RETURN NEW;
END;
$BODY$ LANGUAGE plpgsql VOLATILE;
触发程序与图表文件绑定:
CREATE TRIGGER next_chart
BEFORE INSERT
ON charts
FOR EACH ROW
EXECUTE PROCEDURE next_chart();
我想要做的是在添加新图表记录时替换图表中的空图表编号字段。这可以在触发器中完成吗? (还有什么 是正确的语法??)
答案 0 :(得分:1)
在CREATE FUNCTION next_chart() RETURNS trigger AS $BODY$
BEGIN
-- Check for empty chart number
IF NEW.chart_number IS NULL THEN
WITH ins AS (
SELECT chart_number
FROM chart_gap
WHERE pg_try_advisory_xact_lock(chart_number)
LIMIT 1
)
DELETE FROM chart_gap c
USING ins i
WHERE i.chart_number = c.chart_number
RETURNING i.chart_number INTO NEW.chart_number;
END IF;
RETURN NEW;
END;
$BODY$ LANGUAGE plpgsql VOLATILE;
函数中,您可以使用query RETURNING ... INTO ...
,如下所示:
.headline {
float: right;
}
.btn {
float: left;
}