我正在使用 PostgreSQL 9.5。
我在 PL/pgSQL 中创建一个触发器,当对第二个表执行 INSERT
时,它会向表 (synthese_poly
) 添加一条记录 (operation_poly
), 与其他表数据。
除了一些未填充的变量(尤其是我尝试用 array_to_string()
函数填充的变量)外,触发器运行良好。
这是代码:
-- Function: bdtravaux.totablesynth_fn()
-- DROP FUNCTION bdtravaux.totablesynth_fn();
CREATE OR REPLACE FUNCTION bdtravaux.totablesynth_fn()
RETURNS trigger AS
$BODY$
DECLARE
varoperateur varchar;
varchantvol boolean;
BEGIN
IF (TG_OP = 'INSERT') THEN
varsortie_id := NEW.sortie;
varopeid := NEW.operation_id;
--The following « SELECT » queries take data in third-party tables and fill variables, which will be used in the final insertion query.
SELECT array_to_string(array_agg(DISTINCT oper.operateurs),'; ')
INTO varoperateur
FROM bdtravaux.join_operateurs oper INNER JOIN bdtravaux.operation_poly o ON (oper.id_joinop=o.id_oper)
WHERE o.operation_id = varopeid;
SELECT CASE WHEN o.ope_chvol = 0 THEN 'f' ELSE 't' END as opechvol INTO varchantvol
FROM bdtravaux.operation_poly o WHERE o.operation_id = varopeid;
-- «INSERT» query
INSERT INTO bdtravaux.synthese_poly (soperateur, schantvol) SELECT varoperateur, varchantvol;
RAISE NOTICE 'varoperateur value : (%)', varoperateur;
RAISE NOTICE 'varchantvol value : (%)', varchantvol;
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION bdtravaux.totablesynth_fn()
OWNER TO postgres;
这是触发器:
-- Trigger: totablesynth on bdtravaux.operation_poly
-- DROP TRIGGER totablesynth ON bdtravaux.operation_poly;
CREATE TRIGGER totablesynth
AFTER INSERT
ON bdtravaux.operation_poly
FOR EACH ROW
WHEN ((new.chantfini = true))
EXECUTE PROCEDURE bdtravaux.totablesynth_fn();
varchantvol
变量已正确填充,但 varoperateur
极度空(NULL 值)(对于 synthese_poly
中的相应字段,依此类推> 表格)。
注意:
SELECT array_to_string(…) ...
查询本身(使用 pgAdmin 启动,没有 INTO varoperateur
并用值替换 varopeid
)运行良好,并返回一个字符串。
我试图改变 array_to_string()
函数和变量的数据类型(使用 ::varchar
或 ::text
…),什么都没有作品。
你知道会发生什么吗?
最佳答案
使用array_agg
您可以将 array_to_string(array_agg(DISTINCT oper.operateurs),'; ')
替换为
string_agg(DISTINCT oper.operateurs,'; ')
并且您可以使用order by 对聚合中的文本进行排序
string_agg(DISTINCT oper.operateurs,'; ' ORDER BY oper.operateurs)
关于postgresql - 在 plpgsql 触发器函数中用 "array_to_string"填充变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44072179/