由属性名称参数化的 PostgreSQL 触发器
PostgreSQL trigger parametrized by attribute name
我想创建一个触发器,使所选属性(作为参数给出)首字母大写,其余字母小写。
我想用类似于这个非工作代码的方式来编写它:
CREATE OR REPLACE FUNCTION myTrigger() RETURNS trigger AS
$BODY$
DECLARE
colname TEXT;
newContent TEXT;
BEGIN
colname = TG_ARGV[0];
newContent = format('SELECT ( CONCAT(UPPER(LEFT(NEW.%I,1)),LOWER(SUBSTRING(NEW.%I,2,LENGTH(NEW.%I)))) )', colname, colname, colname);
EXECUTE newContent INTO format('NEW.%I', colname);
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
为什么不能像在控制台中那样在触发器中 EXECUTE
准备语句?
要动态更新 NEW 变量(这意味着,将属性名称作为变量),您可以首先基于 NEW 构建一个 hstore 变量,根据需要操作 hstore 变量,最后使用 [= 更新 NEW 变量11=]:
CREATE OR REPLACE FUNCTION myTrigger() RETURNS trigger AS
$BODY$
DECLARE
colname TEXT;
newContent TEXT;
new_record hstore;
BEGIN
colname = TG_ARGV[0];
-- build a hstore from the NEW variable
new_record= hstore(NEW);
--fetch new content from hstore
newContent = new_record -> colname;
--updating the value
newContent = CONCAT(UPPER(LEFT(newContent,1)),LOWER(SUBSTRING(newContent,2,LENGTH(newContent)))) ;
-- updating hstore content with new value
new_record = new_record || hstore(colname , newContent);
--updating the NEW variable with the populate_record function
NEW = populate_record(NEW,new_record );
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
我想创建一个触发器,使所选属性(作为参数给出)首字母大写,其余字母小写。
我想用类似于这个非工作代码的方式来编写它:
CREATE OR REPLACE FUNCTION myTrigger() RETURNS trigger AS
$BODY$
DECLARE
colname TEXT;
newContent TEXT;
BEGIN
colname = TG_ARGV[0];
newContent = format('SELECT ( CONCAT(UPPER(LEFT(NEW.%I,1)),LOWER(SUBSTRING(NEW.%I,2,LENGTH(NEW.%I)))) )', colname, colname, colname);
EXECUTE newContent INTO format('NEW.%I', colname);
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
为什么不能像在控制台中那样在触发器中 EXECUTE
准备语句?
要动态更新 NEW 变量(这意味着,将属性名称作为变量),您可以首先基于 NEW 构建一个 hstore 变量,根据需要操作 hstore 变量,最后使用 [= 更新 NEW 变量11=]:
CREATE OR REPLACE FUNCTION myTrigger() RETURNS trigger AS
$BODY$
DECLARE
colname TEXT;
newContent TEXT;
new_record hstore;
BEGIN
colname = TG_ARGV[0];
-- build a hstore from the NEW variable
new_record= hstore(NEW);
--fetch new content from hstore
newContent = new_record -> colname;
--updating the value
newContent = CONCAT(UPPER(LEFT(newContent,1)),LOWER(SUBSTRING(newContent,2,LENGTH(newContent)))) ;
-- updating hstore content with new value
new_record = new_record || hstore(colname , newContent);
--updating the NEW variable with the populate_record function
NEW = populate_record(NEW,new_record );
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;