如何使用触发器

时间:2015-08-14 06:16:52

标签: mysql

我需要一个解决方案,在插入记录时将auto increment value复制到userid列。

我有两列,例如id(AI)userid。我在这里使用了一个触发器

CREATE TRIGGER adduserid BEFORE INSERT ON user
 FOR EACH ROW SET NEW.userid = NEW.id 

问题是triggers调用before insert,因此它会将id设为0.

建议我如何修改trigger

1 个答案:

答案 0 :(得分:0)

样品:

表格定义:

CREATE TABLE departments (
ID           NUMBER(10)    NOT NULL,
DESCRIPTION  VARCHAR2(50)  NOT NULL);

ALTER TABLE departments ADD (
CONSTRAINT dept_pk PRIMARY KEY (ID));

CREATE SEQUENCE dept_seq;

触发器定义:

CREATE OR REPLACE TRIGGER dept_bir 
BEFORE INSERT ON departments 
FOR EACH ROW

BEGIN
SELECT dept_seq.NEXTVAL
INTO   :new.id
FROM   dual;
END;

语法Link1:https://dev.mysql.com/doc/refman/5.0/en/create-trigger.html