MYSQL DATE_ADD区间作为另一列的变量OR

时间:2016-09-19 15:37:32

标签: mysql dateadd

我正在尝试在我的桌面上创建一个事件,每隔几分钟运行一次以查看'next_run'是否为now(),如果是,则将'frequency'添加到'next_run',但每次我都会收到语法异常

下面是表格结构......

     LAST_RUN       |FREQUENCY|   NEXT_RUN 
----------------------------------------------------
2016-09-15 06:02:06 | 1 DAY   | 2016-09-15 06:02:06

” 我正在使用的代码就是这个......

UPDATE TASKS_MASTER_COPY 
@num:=CAST(FREQUENCY) AS UNSIGNED,
@p  :=SUBSTR(FREQUENCY, CHAR_LENGTH(@num)+2)
LAST_RUN=NEXT_RUN,
NEXT_RUN=NEXT_RUN + CASE
        WHEN @p='YEAR' THEN DATE_ADD(NEXT_RUN, INTERVAL @num YEAR)
        WHEN @p='MONTH' THEN DATE_ADD(NEXT_RUN, INTERVAL @num MONTH)
        WHEN @p='DAY' THEN DATE_ADD(NEXT_RUN, INTERVAL @num DAY)
        WHEN @p='WEEK' THEN DATE_ADD(NEXT_RUN, INTERVAL @num WEEK)
            END
WHERE TASK_MASTER_ID=100;

有人可以帮我这个吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

此版本对我没有错误:

UPDATE TASKS_MASTER_COPY
SET
LAST_RUN = NEXT_RUN,
NEXT_RUN = NEXT_RUN +
  CASE
    WHEN SUBSTR(FREQUENCY, CHAR_LENGTH(CAST(FREQUENCY AS UNSIGNED)) + 2) = 'YEAR'
    THEN DATE_ADD(NEXT_RUN, INTERVAL CAST(FREQUENCY AS UNSIGNED) YEAR )
    WHEN SUBSTR(FREQUENCY, CHAR_LENGTH(CAST(FREQUENCY AS UNSIGNED)) + 2) = 'MONTH'
    THEN DATE_ADD(NEXT_RUN, INTERVAL CAST(FREQUENCY AS UNSIGNED) MONTH)
    WHEN SUBSTR(FREQUENCY, CHAR_LENGTH(CAST(FREQUENCY AS UNSIGNED)) + 2) = 'DAY'
    THEN DATE_ADD(NEXT_RUN, INTERVAL CAST(FREQUENCY AS UNSIGNED) DAY  )
    WHEN SUBSTR(FREQUENCY, CHAR_LENGTH(CAST(FREQUENCY AS UNSIGNED)) + 2) = 'WEEK'
    THEN DATE_ADD(NEXT_RUN, INTERVAL CAST(FREQUENCY AS UNSIGNED) WEEK )
  END
WHERE TASK_MASTER_ID = 100;

一些问题:

  • CAST(FREQUENCY AS UNSIGNED)不是CAST(FREQUENCY) AS UNSIGNED
  • UPDATE在表名
  • 后需要SET
  • 我认为UPDATE只能包含要更新的列,且不能包含@num@p

基于https://stackoverflow.com/a/22404258/761771