如何插入名称作为变量存储在同一脚本中的 table?
How to INSERT into a table whose name is stored as variable inside the same script?
为了简要说明问题,我有一个名为 partitions_info
的 table,它维护我正在使用的所有其他 table 的详细信息。
partitions_info
的列是 tablename
、starttime
、endtime
我编译了以下触发器,用于根据某些条件从 partitions_info
table(如上所示的架构)中选择特定的 table 名称。
我将 table 名称存储到变量 table_name
中。现在如何将一些值插入存储在变量 table_name
中的 table?
CREATE OR REPLACE FUNCTION emp_fun()
RETURNS TRIGGER AS
$$
DECLARE
table_name varchar(65);
BEGIN
SELECT tablename FROM partitions_info INTO table_name WHERE starttime<'2015-12-04 14:23:56' AND endtime>'2015-12-04 14:23:56';
IF table_name IS NULL THEN
INSERT INTO default_table VALUES (NEW.*);
END IF;
# Here I wanted to insert into table name which is stored in variable whose name is stored in "table_name" variable declared above
RETURN NEW;
END;
$$
LANGUAGE plpgsql;
动态 INSERT
的实现可能如下所示(包括其他一些小的改进):
CREATE OR REPLACE FUNCTION emp_fun()
RETURNS TRIGGER AS
$func$
DECLARE
table_name text;
BEGIN
SELECT INTO table_name p.tablename
FROM partitions_info p
WHERE p.starttime < '2015-12-04 14:23:56'
AND p.endtime > '2015-12-04 14:23:56';
IF FOUND THEN -- simpler, cheaper, safer
<b> EXECUTE 'INSERT INTO ' || quote_ident(table_name) || ' VALUES (.*)'
USING NEW;</b>
ELSE
INSERT INTO default_table VALUES (NEW.*);
END IF;
RETURN NEW;
END
$func$ LANGUAGE plpgsql;
相关:
- INSERT with dynamic table name in trigger function
- PL/pgSQL: General Way to Update N Columns in Trigger?
- Self-managing PostgreSQL partition tables
为了简要说明问题,我有一个名为 partitions_info
的 table,它维护我正在使用的所有其他 table 的详细信息。
partitions_info
的列是 tablename
、starttime
、endtime
我编译了以下触发器,用于根据某些条件从 partitions_info
table(如上所示的架构)中选择特定的 table 名称。
我将 table 名称存储到变量 table_name
中。现在如何将一些值插入存储在变量 table_name
中的 table?
CREATE OR REPLACE FUNCTION emp_fun()
RETURNS TRIGGER AS
$$
DECLARE
table_name varchar(65);
BEGIN
SELECT tablename FROM partitions_info INTO table_name WHERE starttime<'2015-12-04 14:23:56' AND endtime>'2015-12-04 14:23:56';
IF table_name IS NULL THEN
INSERT INTO default_table VALUES (NEW.*);
END IF;
# Here I wanted to insert into table name which is stored in variable whose name is stored in "table_name" variable declared above
RETURN NEW;
END;
$$
LANGUAGE plpgsql;
动态 INSERT
的实现可能如下所示(包括其他一些小的改进):
CREATE OR REPLACE FUNCTION emp_fun()
RETURNS TRIGGER AS
$func$
DECLARE
table_name text;
BEGIN
SELECT INTO table_name p.tablename
FROM partitions_info p
WHERE p.starttime < '2015-12-04 14:23:56'
AND p.endtime > '2015-12-04 14:23:56';
IF FOUND THEN -- simpler, cheaper, safer
<b> EXECUTE 'INSERT INTO ' || quote_ident(table_name) || ' VALUES (.*)'
USING NEW;</b>
ELSE
INSERT INTO default_table VALUES (NEW.*);
END IF;
RETURN NEW;
END
$func$ LANGUAGE plpgsql;
相关:
- INSERT with dynamic table name in trigger function
- PL/pgSQL: General Way to Update N Columns in Trigger?
- Self-managing PostgreSQL partition tables