如何在插入之前使用mysql触发器生成动态ID

时间:2019-03-06 06:39:46

标签: mysql triggers

我需要生成20191B01;之类的student_roll_no,我想增加20191B02,..........20191B10,20191B11之类的student_roll_no的后两位。使用以下代码,我可以在20191B09之后开始20191B010,但我需要20191B10

SET NEW.student_roll_no = CONCAT(
   YEAR(CURRENT_DATE), 
   NEW.class_code,
   IFNULL(CONCAT('0',(substring((SELECT student_roll_no FROM students WHERE class_code = NEW.class_code ORDER BY created_at DESC LIMIT 1),-2)+1)),'01'))

2 个答案:

答案 0 :(得分:0)

如果您固定了两位数的学生编号,请使用LPAD。 Reference

否则,此代码段可能会有所帮助:

#!/bin/bash
sops_ops() {
    sops --version
    if [ "$?" -eq "0" ]; then
        echo "proceed sops ops"
    else
        echo "check sops binary"
    fi

    read -p 'Enter cluster_NAME: = ' CLUSTER_NAME
    test_environment="test.com"
    test1_environment="test1.com"
    test2_environment="test2.com"

    case "${$CLUSTER_NAME}" in
      prod.$test_environment) ;;
      dev.$test1_environment) ;;
      stage.$test2_environment) ;;
      test.$test_environment) ;;
      *) echo "Invalid option: ${CLUSTER_NAME}" 1>&2 && exit 1 ;;

    if [ $CLUSTER_NAME = test.$test_env ];then
        printf "got cluster $CLUSTER_NAME"
    elif [ $CLUSTER_NAME = "test.test.com" ];then
        printf "got dev cluster $CLUSTER_NAME"
        echo "not found cluster"
    else
        echo "Environment not available"
    fi
}
sops_ops

答案 1 :(得分:0)

使用以下代码解决您的问题。

SET @roll_num = IFNULL((substring((SELECT student_roll_no FROM students WHERE class_code = NEW.class_code ORDER BY created_at DESC LIMIT 1),-2) +1),'1'),
NEW.student_roll_no = CONCAT(YEAR(CURRENT_DATE), NEW.class_code, 
        IF (    
           @roll_num < 10,
           CONCAT('0',@roll_num),
           @roll_num
       )
)