我有一个名为> Project的表,其中包含一个自动增量字段,用于调用项目估算出价编号Project_ID.
该字段自动递增.我创建了一个带有字段规则的8位字符字段.
我需要它自动递增为两个数字年,两个数字月,包括一个连字符,然后在该时间段内从第一个记录的001开始的数字.
2012年4月的一个例子是第一个记录为1204-001,第二个记录为1204-002等等,然后当5月份在Project_ID周围滚动时将变为1205-001.
我一直在尝试编写的内容如下,我将其保留为默认值为默认值的简单默认表达式
Cyear(date()) + (month()) + “-“ + “001” .
Run Code Online (Sandbox Code Playgroud)
我是如何实现这一目标的?
基本上,您可以在想要增加列的表上使用BEFORE INSERT 。 TRIGGER
以下是创建简单算法并将此代码放入触发器中的一些步骤:
// get current YEAR
SET @cur_Year = CONCAT(DATE_FORMAT(CURDATE(), '%Y'));
// get current MONTH
SET @cur_MONTH = CONCAT(DATE_FORMAT(CURDATE(), '%m'));
// concatenate YEAR and MONTH
SET @Year_Month = CONCAT(@cur_Year, @cur_MONTH);
// get the last value for the current YEAR and MONTH
SET @max_ID = ( SELECT MAX(ID)
FROM tableName
WHERE ID LIKE CONCAT(@Year_Month, '-%'));
// get the last three characters from the id, convert in to
// integer and increment by 1
SET @last_ID = CAST(RIGHT(@max_ID, 3) AS SIGNED) + 1;
// pad zero on the left using LPAD and
// concatenate it with YEAR and MONTH
SET @new_ID = CONCAT(@Year_Month,'-',LPAD(CAST(@last_ID AS CHAR(3)), 3, '0'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1463 次 |
| 最近记录: |