0

我有一个 jdbc 客户端与 postgresql 数据库通信。从 JDBC 为在表上插入一些数据创建一个准备好的语句,但是在创建查询的那一刻,客户端不知道要在语句中插入的所有字段,并且为了完成查询,我编写了一个触发的 TRIGGER在插入该表之前,找到缺失值,继续执行查询。这是jdbc代码:

String MY_INSERT = "INSERT INTO myTable VALUES(?, ?, ?, ?, ?, ?)";
PreparedStatement pstm = connection.PrepareStatement(MY_INSERT);
pstm5.setInt(1, 2562);
pstm5.setInt(2, 22);
pstm5.setInt(3, 0); //unknown value, set to zero
pstm5.setString(4, "a string");
pstm5.setInt(5, 0); //the other unknown value

这是触发代码:

CREATE FUNCTION perform_() RETURNS trigger AS $myTrigger$

DECLARE 
vend VARCHAR(20);
pre numeric(10,2);

BEGIN
    SELECT field3, field5 FROM otherTable WHERE id = NEW.field2 INTO vend, pre;

    NEW.field3 = vend;
    NEW.field5 = pre;

    RETURN NULL;
END;
$myTrigger$ LANGUAGE plpgsql;

CREATE TRIGGER myTrigger
BEFORE INSERT ON myTable
EXECUTE PROCEDURE perform_(); 

当触发器触发我有这个错误:

Exception: JDBCClass error: ERROR: record "new" is not assigned yet
Details: The tuple structure of a not-yet-assigned record is indeterminate.
SELECT field3, field5 FROM otherTable WHERE id = NEW.field2 INTO vend, pre;

这是什么意思?记录新分配的内容,如您在 jdbc 代码中所见...

4

1 回答 1

1

首先,您错过FOR EACH ROW了触发器声明:

CREATE TRIGGER myTrigger
BEFORE INSERT ON myTable
FOR EACH ROW EXECUTE PROCEDURE perform_(); 

其次,return NEW;如果您希望将记录插入表中,则必须这样做

参见sql fiddle 演示

于 2013-08-16T09:20:26.250 回答