0

i need a help to format this trigger output.

I need the output of the trigger have this format:

2013/0001
2013/0002
...

When year changes,

2014/0001
2014/0002
...

but my trigger generates that format:

00012013/

The trigger code is below:

SET NEW.num = CONCAT(
LPAD(COALESCE(
  (SELECT MAX(LEFT(num, 4)) 
     FROM `tb_numeros`
    WHERE num LIKE DATE_FORMAT(CURDATE(), '%Y/____')), 0) + 1, 4, '0'), 
DATE_FORMAT(CURDATE(), '%Y/'))

3 Answers 3

1

You can use indentation to clarify what's going on:

SET NEW.num = CONCAT(
    LPAD(
        COALESCE(
            (
                SELECT MAX(LEFT(num, 4)) 
                FROM `tb_numeros`
                WHERE num LIKE DATE_FORMAT(CURDATE(), '%Y/____')
            ), 0
        ) + 1, 4, '0'
    ), 
    DATE_FORMAT(CURDATE(), '%Y/')
)

It's clear that you get year on second place because, well, it's the second clause inside CONCAT().

Sign up to request clarification or add additional context in comments.

2 Comments

Im trying change order, but generates mysql error. Any sugestion about his order?
How could I suggest anything? I don't know how you changed the code or what error you get now.
1

I do not understand how you get the number sequence, however, I think you can simplify the code a bit:

...
SET `get_year` := YEAR(NOW());
SET `sequence` := (SELECT... WHERE... `num`... LIKE... `get_year`...); /* RETURN 0001 */
SET NEW.`num` := CONCAT(`get_year`, '/', `sequence`);
...

Comments

0

yeah! woRKS!!!

SET NEW.num = CONCAT(
DATE_FORMAT(CURDATE(), '%Y/'),
LPAD(
    COALESCE(
        (
            SELECT MAX(RIGHT(num, 4)) 
            FROM `tb_numeros`
            WHERE num LIKE DATE_FORMAT(CURDATE(), '%Y/____')
        ), 0
    ) + 1, 4, '0'
)
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.