1
customers:
+------------+--------------+ 
| cid        | Name         | 
+------------+--------------+ 
| 1          | Bob          |
| 2          | John         | 
| 3          | Jane         | 
+------------+--------------+ 
accounts:
+------------+--------------+ 
| aid        | type         | 
+------------+--------------+ 
| 1          | Checking     |
| 2          | Saving       | 
| 3          | Checking     | 
+------------+--------------+ 
transactions:
+------------+--------------+--------------+--------------+ 
| tid        | cid          | aid          | type         |
+------------+--------------+--------------+--------------+ 
| 1          | 1            | 1            | Open         |
| 2          | 2            | 3            | Open         |
| 3          | 1            | 2            | Open         |
| 4          | 2            | 3            | Deposit      |
+------------+--------------+--------------+--------------+

我正在尝试编写一个触发器,当新帐户成功打开时写入日志表。

现在我有这个:

CREATE OR REPLACE TRIGGER acc_opened
BEFORE INSERT ON transactions
FOR EACH ROW
DECLARE
    c_name customers.name%TYPE;
BEGIN
    IF :new.type = 'Open' THEN
        SELECT name into c_name
        FROM customers c
        WHERE c.cid = :new.cid;

        INSERT INTO logs (who, what) VALUES (c_name, 'An account has been opened');
END;
/    

我的代码不起作用,也不知道从哪里开始。

触发器完成,但是当它触发时,我收到以下错误消息:

PLS-00103:在预期以下情况之一时遇到符号“END”:(begin case declare exit for goto if loop mod null pragma raise return select update while with << continue close current delete fetch lock insert open rollback savepoint set sql execute提交 forall 合并管道清除

4

1 回答 1

0

上一个问题一样,如果要引用新数据行的特定列,则需要使用:new伪记录。所以,至少,

SELECT cid 
  INTO c_id
  FROM transactions t
 WHERE t.aid = aid;

需要是

SELECT cid 
  INTO c_id
  FROM transactions t
 WHERE t.aid = :new.aid;

transactions除此之外,在将行插入accounts故事之前,您确定该行存在于表中吗?假设您有正常的外键约束,我通常希望您先在表中插入一行,accounts然后再将行插入transactions表中。

这个名字transactions似乎也很奇怪。如果这真的只是将客户 ID 映射到帐户 ID,那transactions似乎是一个相当糟糕的名称。如果该表实际存储交易,我不确定它为什么会有客户 ID。但如果它确实存储交易,则必须有一些其他表将客户映射到帐户。

在您更新的触发器中,您缺少该END IF语句

CREATE OR REPLACE TRIGGER acc_opened
  BEFORE INSERT ON transactions
  FOR EACH ROW
DECLARE
  c_name customers.name%TYPE;
BEGIN
  IF :new.type = 'Open' 
  THEN
    SELECT name 
      into c_name
      FROM customers c
     WHERE c.cid = :new.cid;

     INSERT INTO logs (who, what) 
       VALUES (c_name, 'An account has been opened');
  END IF;
END;
于 2012-12-07T05:18:03.960 回答