gpt4 book ai didi

postgresql - 遍历所有用户表并在每个表中插入行

转载 作者:行者123 更新时间:2023-11-29 11:49:53 35 4
gpt4 key购买 nike

出于某种原因,我无法弄清楚这一点。我在 PostgreSQL 中有一个单独的模式,用于连接到服务器的每个用户的通知相关表。我的计划是让每个用户创建一个 TEMP 表来接收额外的通知信息,因为 Xojo 不支持 PostgreSQL 负载。
我觉得我开始接近了,所以我将只发布我的触发函数中的代码。

    DECLARE
my_table RECORD;
BEGIN
FOR my_table IN
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'information_schema'
LOOP
INSERT INTO my_table.table_name (effected_row_id)
VALUES (NEW.effected_row_id);
END LOOP;
END;

如果我错了请告诉我,但我相信我的主要问题是弄清楚如何在 INSERT 语句中使用从 SELECT 语句返回的表名。

编辑:这是我当前的触发函数

-- Function: notification.my_insert_trigger_function()

-- DROP FUNCTION notification.my_insert_trigger_function();

CREATE OR REPLACE FUNCTION notification.my_insert_trigger_function()
RETURNS trigger AS
$BODY$DECLARE
my_table RECORD;
BEGIN
FOR my_table IN
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'notification' AND table_name <> 'notification_global' AND table_name <> 'switcher'
LOOP
EXECUTE(FORMAT($f$
INSERT INTO %s (effected_row_username)
VALUES (%s);
$f$, 'notification.' || my_table.table_name, NEW.effected_row_username));
END LOOP;
RETURN new;
END;$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION notification.my_insert_trigger_function()
OWNER TO serveradmin;

最佳答案

您需要使用 dynamic commands在你的触发功能中。函数format()通常很有帮助。

DECLARE
my_table RECORD;
BEGIN
FOR my_table IN
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'information_schema'
LOOP
EXECUTE(FORMAT($f$
INSERT INTO %s (effected_row_id)
VALUES (%s);
$f$, my_table.tablename, NEW.effected_row_id));
END LOOP;
END;

关于postgresql - 遍历所有用户表并在每个表中插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33423006/

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