简体   繁体   中英

Auto_increment trigger

I need to auto_increment the primary key in a mysql database using a trigger. Unfortunately, I am not quite sure how to do this. In the sample code I have provided, I need the employee table primary key to auto_increment beginning with an empty table and a starting value of 200. Then, I need each new insert to increment by 1.Thanks for looking and I hope you are able to help me.

CREATE TABLE department (
dept_name VARCHAR(50) NOT NULL  Primary Key
);

CREATE TABLE employee (
emp_id INT(6) unsigned Default 0 Not NULL 
, last_name VARCHAR(25) NOT NULL
, first_name VARCHAR(40) NOT NULL
, dept_name VARCHAR(50) NOT NULL
, PRIMARY KEY(emp_id, dept_name)
,  FOREIGN KEY(dept_name) REFERENCES department (dept_name)
);

There are several things you need to do:

  1. Declare the emp_id column as AUTO_INCREMENT ;
  2. Set the value of AUTO_INCREMENT property of the table to 200 ;
  3. Do not provide any value for column emp_id when you INSERT rows in table employee .

Change the table creation as below:

CREATE TABLE employee (
    emp_id INT(6) UNSIGNED NOT NULL AUTO_INCREMENT,
    last_name VARCHAR(25) NOT NULL,
    first_name VARCHAR(40) NOT NULL,
    dept_name varchar(50) NOT NULL
    PRIMARY KEY(emp_id),
    FOREIGN KEY(dept_name) REFERENCES department_tbl(dept_name)
) AUTO_INCREMENT=200;

If the table has an AUTO_INCREMENT column then it must be the PRIMARY KEY of the table. I removed dept_name from the definition of the PK above. I also removed the default value 0 from the emp_id column. It's default value is generated by MySQL using the AUTO_INCREMENT policy.

When you INSERT a new record into the employee table all you have to do is to not provide any value for the emp_id column:

INSERT INTO employee (last_name, first_name, dept_name)
VALUES ('Doe', 'John', 'accounting');

Then use the LAST_INSERT_ID() MySQL function to retrieve the value of the emp_id generated on insertion.

The language or the library you use to develop the client application probably has a function that wraps LAST_INSERT_ID() and returns its value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM