Question

How can i implement two auto increment fields in a table. i found this can be done with trigger.

already done trigger autoincrement for varchar field, now need autocrement for another field (int)

Trigger
========

DELIMITER $$
CREATE TRIGGER tg_customer_details_insert
BEFORE INSERT ON customer_details
FOR EACH ROW
BEGIN
  INSERT INTO customer_details_seq VALUES (NULL);
  SET NEW.Customer_id = CONCAT('CUST', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;

What i need is to set auto increment for fields "customer_id" and "Slno".

where Customer_id (Varchar) is Primary Key and done auto increment using the above trigger.

Now i need to add auto increment for Slno (Int) in the same table.

Thanks, Acube

Was it helpful?

Solution

One way is something like this:

DELIMITER $$
CREATE TRIGGER tg_customer_details_insert
BEFORE INSERT ON customer_details
FOR EACH ROW
BEGIN
    set NEW.IntId = coalesce((select max(IntId) from customer_details), 0) + 1;
END$$
DELIMITER ;

But why not just use an auto_increment column? That is what it is there for.

OTHER TIPS

The following trigger can do the job you need:

DELIMITER $$

CREATE TRIGGER `tg_customer_details_insert` BEFORE INSERT ON `customer_details`
FOR EACH ROW
BEGIN
    INSERT INTO `customer_details_seq` (`id`) VALUES (0);
    SET NEW.`customer_id` := CONCAT('CUST', LPAD(LAST_INSERT_ID(), 3, '0'));
END*/$$

DELIMITER ;

SQL Fiddle demo

The strange thing about the design that need another sequence for the customer_id column of the table customer_details. Why is that?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top