我正在尝试创建一种机制,每次在它们上面调用insert命令时都会截断表。
首先,我尝试创建一个获取行数组并在插入表之前截断表的函数:
CREATE OR REPLACE FUNCTION insert_customers(customers customer[])
RETURNS VOID AS
$$
BEGIN
TRUNCATE TABLE Customers;
INSERT INTO Customers (CustomerID, CustomerName) SELECT * FROM UNNEST(customers::Customer[]);
END
$$
LANGUAGE plpgsql;
Customer是用户定义的类型,表示Customers表中的行:
CREATE TYPE Customer AS (
customerid VARCHAR(100),
customername VARCHAR(100));
当我从psql调用函数时,这很有效:
SELECT * FROM insert_customers(ARRAY[ROW('ID1', 'Name1'),ROW('ID2', 'Name2')]::Customer[]);
但我还没有找到一种方法从我的java代码中执行这个插入:
String[][] customers = new String[2][];
customers[0] = new String[] { "ID1", "Name1" };
customers[1] = new String[] { "ID2", "Name2" };
Array sqlArray = connection.createArrayOf("customer", customers);
CallableStatement cstmt = connection.prepareCall("{ call insert_customers(?) }");
cstmt.setArray(1, sqlArray);
cstmt.execute();
创建了以下声明:
select * from insert_customers ('{{"ID1", "Name1"},{"ID2", "Name2"}}') as result
并抛出以下异常:
org.postgresql.util.PSQLException: ERROR: malformed record literal: "ID1"\n Detail: Missing left parenthesis.
然后我尝试创建一个触发器,它将在insert事件上截断表:
CREATE TRIGGER on_insert_customers
BEFORE INSERT ON Customers
EXECUTE PROCEDURE truncate_customers();
truncate_customers 是:
CREATE OR REPLACE FUNCTION truncate_customers()
RETURNS TRIGGER AS
$$
BEGIN
TRUNCATE TABLE Customers;
END
$$
LANGUAGE plpgsql;
这引发了例外:
cannot TRUNCATE "customers" because it is being used by active queries in this session
任何想法???
答案 0 :(得分:1)
查询文本数组中不需要的元素对:
select cols[1], cols[2]
from (
select (ordinality- 1)/2, array_agg(unnest) cols
from unnest('{"id1", "name1", "id2", "name2"}'::text[]) with ordinality
group by 1
) s
cols | cols
------+-------
id1 | name1
id2 | name2
(2 rows)
在函数中使用它,以便它可以将文本数组作为参数:
create or replace function insert_customers(text[])
returns void language plpgsql as $$
begin
truncate table customers;
insert into customers (customerid, customername)
select cols[1], cols[2]
from (
select (ordinality- 1)/2, array_agg(unnest) cols
from unnest($1) with ordinality
group by 1
) s;
end $$;
select insert_customers('{"id1", "name1", "id2", "name2"}');
您不能在触发器中截断表,但可以删除所有行:
...
delete from Customers;
return new;
...