gpt4 book ai didi

postgresql - 如何在 postgresql 中正确实现软删除?

转载 作者:行者123 更新时间:2023-11-29 13:21:03 25 4
gpt4 key购买 nike

在我的 postgres 9.3 数据库中,我有以下函数和触发器的组合来实现软删除功能:

ALTER TABLE "LIBN02"."trigger_test_1"
ADD COLUMN delete_ind integer

CREATE OR REPLACE FUNCTION trigger_test_1_soft_delete()
RETURNS trigger AS $$
DECLARE
command text := ' SET delete_ind = 1 WHERE uuid_col = $1';
BEGIN
EXECUTE 'UPDATE ' || "LIBN02"."trigger_test_1" || command USING OLD.uuid_col;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER test_1_soft_delete_trigger
BEFORE DELETE ON "LIBN02"."trigger_test_1"
FOR EACH ROW EXECUTE PROCEDURE trigger_test_1_soft_delete();

完成上述所有操作后,我运行以下删除语句:

DELETE FROM "LIBN02"."trigger_test_1"

我收到以下错误:

ERROR:  missing FROM-clause entry for table "LIBN02"
LINE 1: SELECT 'UPDATE ' || "LIBN02"."trigger_test_1" || command
^
QUERY: SELECT 'UPDATE ' || "LIBN02"."trigger_test_1" || command
CONTEXT: PL/pgSQL function trigger_test_1_soft_delete() line 5 at EXECUTE

********** Error **********

ERROR: missing FROM-clause entry for table "LIBN02"
SQL state: 42P01
Context: PL/pgSQL function trigger_test_1_soft_delete() line 5 at EXECUTE

我应该更改什么才能使其正常工作?

最佳答案

您收到的错误是因为 "LIBN02"."trigger_test_1" 不是字符串(用单引号引起来),而是一个标识符。你应该使用

EXECUTE 'UPDATE "' || TG_TABLE_SCHEMA || '"."' || TG_TABLE_NAME || '" ' || command
USING OLD.uuid_col;

您还可以将 AND NOT deleted 添加到 WHERE 子句以避免不必要的流失。

关于postgresql - 如何在 postgresql 中正确实现软删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41752660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com