我有以下触发功能:
CREATE OR REPLACE FUNCTION update_modelname_function()
RETURNS trigger AS
$BODY$
BEGIN
IF tg_op = 'INSERT' THEN
new.model_name := upper(new.model_name);
RETURN new;
END IF;
IF tg_op = 'UPDATE' THEN
old.model_name := upper(old.model_name);
RETURN new;
END IF;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
我想要实现的是当列model_name的值在表中持久存在时始终是大写的。但似乎没有任何事情发生。有什么想法吗?
答案 0 :(得分:5)
您意外更新了old
而不是new
。尝试:
CREATE OR REPLACE FUNCTION update_modelname_function()
RETURNS trigger AS
$BODY$
BEGIN
IF tg_op = 'INSERT' THEN
new.model_name := upper(new.model_name);
RETURN new;
ELSIF tg_op = 'UPDATE' THEN
new.model_name := upper(new.model_name);
RETURN new;
END IF;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
如果示例显示整个代码,并且实际触发器仅在INSERT
和/或UPDATE
上触发,则可以进一步简化:
CREATE OR REPLACE FUNCTION update_modelname_function()
RETURNS trigger AS
$BODY$
BEGIN
new.model_name := upper(new.model_name);
RETURN new;
END
$BODY$
LANGUAGE plpgsql VOLATILE;