views:

112

answers:

2

Hi there,

I want to insert multiple values in a table where the value in one of the column increments sequentially. However, the sequence is a bit complex because of business requirements.

The single insert would go something like this:

INSERT INTO blah (col1, col2) VALUES ('SU0001', 'myemail');

Now, col1 is the value that needs to increment, but keep the fixed length structure. So the next insert should be like this:

INSERT INTO blah (col1, col2) VALUES ('SU0002', 'myemail');

and so on.. till:

INSERT INTO blah (col1, col2) VALUES ('SU1600', 'myemail');

How can I do this with SQL only. I can easily do this in Java and Ruby, but am stuck at this and have tried several things, but most don't seem to keep the fixed length structure (It become SU1, SU2, instead of SU0001, SU0002).

Thanks for all help!

Vikram

A: 

create TEMPORARY TABLE with 0-9

after this compose query that joins that table self as much times as needed (2 - for 00 - 99, etc)

after this do INSERT ... SELECT from subquery

;-)

and LPAD() for leading zeros

zerkms
Sorry to be such a dork, but could you give me a little bit of example with a query?
Vikram Goyal
SELECT CONCAT(t1.num, t2.num) FROM table t1 INNER JOIN table t2or t1.num * 10 + t2.num instead of CONCAT()
zerkms
+2  A: 

Since you've already got the increment down, it appears all you're missing is LPAD.

LPAD(@i, 4, '0')

will add repetitions of '0' to the left of @i so that the resulting string is at least 4 characters wide.

You could even put the increment logic in a trigger.

delimiter //
CREATE TRIGGER incr_col1 BEFORE INSERT ON blah
FOR EACH ROW BEGIN
  SET @prev=(SELECT COALESCE(MAX(col1), 0) FROM blah);
  SET NEW.col1 = CONCAT('SU', LPAD(1+SUBSTR(@prev, 3), 4, '0'));
END //
delimiter ;
outis