MySQL 用户定义函数使用日期自动增加值

MySQL user defined function auto increment value using Date

我能够获得以下代码来创建一个函数,该函数有助于根据输入的日期和行数生成自动增量值。但是我无法让它在 MySQL 中执行。我以前从未创建过用户定义函数,所以请帮助更正代码。 (此代码由MSSQL查询转换而来)


CREATE FUNCTION udf_ComputeColumn (p_id int, p_CreateDate date)
RETURNS char(8) 
BEGIN
   DECLARE v_revtal char(8);
   DECLARE v_NumberOfRowsToday bigint;

-- get the number of rows inserted in the same day before the current row
SELECT COUNT(*) INTO v_NumberOfRowsToday 
FROM tickreqs
WHERE createdate= p_CreateDate
AND id < p_id;

-- calculate the string to return
SET v_revtal = DATE_FORMAT (p_CreateDate, 12) + RIGHT('0000' + 
CAST(v_NumberOfRowsToday as varchar(1)), 4);
RETURN v_revtal; 

END;

*table tickreqs 有一个 id 列和 createdate 列。

下面的代码完成了工作,但可能需要稍作调整。


CREATE TRIGGER GenRequestCode BEFORE INSERT ON tickreqs FOR EACH ROW
BEGIN
  SET NEW.codeyear = YEAR(NOW());
  SET NEW.requestcode = (SELECT IFNULL( MAX(requestcode) , 0 ) + 1 FROM tickreqs WHERE codeyear=YEAR(NOW()));
END

下面的代码将为您提供 20170001 20170002 等代码。


CREATE TRIGGER GenRequestCode BEFORE INSERT ON tickreqs FOR EACH ROW
BEGIN
   DECLARE v_NumberOfRowsToday BIGINT;
   SELECT COUNT(*) INTO v_NumberOfRowsToday FROM tickreqs WHERE YEAR(createdate) = YEAR(NOW());
   SET NEW.requestcode = concat(YEAR(Now()), RIGHT(CONCAT('0000', 
CONVERt(v_NumberOfRowsToday + 1, CHAR)), 4));
END