触发器,其中 logs/deletes 行变成单独的 table,然后插入具有相同属性值的条目
Trigger, which logs/deletes a row into a separate table, before an entry with the same attribute value is inserted
我有两个 table,它们都有相同的列和一个名为 id
的外键。 Table t1
应该存储当前数据,而 table t2
是日志 table.
table t1
中的行应该是唯一的,所以我想创建一个触发器,将数据从 t1
复制到 t2
,然后删除t1
中的条目(如果我插入具有已在 t1
中找到的 ID 的数据)。
如果在 t1
中找不到 id,触发器应该只是将数据插入 t1
并且不对 t2
执行任何操作。我正在使用 PostgreSQL,这是我目前的尝试,但它似乎不起作用:
CREATE OR REPLACE FUNCTION move_data_to_historical_measured_data_insert()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS
$$
BEGIN
IF OLD.id = NEW.id THEN
INSERT INTO t2(id, value, timestamp)
VALUES(OLD.id, OLD.value, OLD.timestamp);
DELETE FROM t1;
RETURN NULL;
ELSE
RETURN NULL;
END IF;
END;
$$
CREATE OR REPLACE TRIGGER store_data_to_history_insert
BEFORE INSERT
ON t1
FOR EACH ROW
EXECUTE PROCEDURE move_data_to_historical_measured_data_insert();
CREATE OR REPLACE FUNCTION move_data_to_historical_measured_data_insert()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
begin
if (exists(select t1.id from t1 where t1.id = new.id)) then
insert into t2 (id, value, timestamp)
select t1.id, t1.value, t1.timestamp from t1 where t1.id = new.id;
delete from t1 where t1.id = new.id;
end if;
return new;
END;
$function$
;
CREATE OR REPLACE TRIGGER store_data_to_history_insert
BEFORE INSERT
ON t1
FOR EACH ROW
EXECUTE PROCEDURE move_data_to_historical_measured_data_insert();
我有两个 table,它们都有相同的列和一个名为 id
的外键。 Table t1
应该存储当前数据,而 table t2
是日志 table.
table t1
中的行应该是唯一的,所以我想创建一个触发器,将数据从 t1
复制到 t2
,然后删除t1
中的条目(如果我插入具有已在 t1
中找到的 ID 的数据)。
如果在 t1
中找不到 id,触发器应该只是将数据插入 t1
并且不对 t2
执行任何操作。我正在使用 PostgreSQL,这是我目前的尝试,但它似乎不起作用:
CREATE OR REPLACE FUNCTION move_data_to_historical_measured_data_insert()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS
$$
BEGIN
IF OLD.id = NEW.id THEN
INSERT INTO t2(id, value, timestamp)
VALUES(OLD.id, OLD.value, OLD.timestamp);
DELETE FROM t1;
RETURN NULL;
ELSE
RETURN NULL;
END IF;
END;
$$
CREATE OR REPLACE TRIGGER store_data_to_history_insert
BEFORE INSERT
ON t1
FOR EACH ROW
EXECUTE PROCEDURE move_data_to_historical_measured_data_insert();
CREATE OR REPLACE FUNCTION move_data_to_historical_measured_data_insert()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
begin
if (exists(select t1.id from t1 where t1.id = new.id)) then
insert into t2 (id, value, timestamp)
select t1.id, t1.value, t1.timestamp from t1 where t1.id = new.id;
delete from t1 where t1.id = new.id;
end if;
return new;
END;
$function$
;
CREATE OR REPLACE TRIGGER store_data_to_history_insert
BEFORE INSERT
ON t1
FOR EACH ROW
EXECUTE PROCEDURE move_data_to_historical_measured_data_insert();