在将来插入MySQL日期x天而不是周末

时间:2014-07-10 15:36:50

标签: mysql

我有以下触发器。目标是在警报表中插入一个日期,该日期距离NOW()最近14天,而该日期不是周末。目标代码以" INSERT INTO alarm"开头。下面。我很难过。谢谢你的帮助。

  DELIMITER |
    CREATE TRIGGER Invoice_Funnel_AfterUpdate
        AFTER UPDATE ON INVOICE
        FOR EACH ROW BEGIN
        IF (OLD.status != NEW.status && NEW.status in ("1","5","7")
        THEN
          UPDATE customers
          SET set sales_funnel_status = '5', sales_funnel_status_date = NOW()
          WHERE customerID = OLD.customerID LIMIT 1 

INSERT INTO alarms (username, createdBy, customerID, date_stamp, alert_stamp, minutes_before, active, subject, note,timestamp,funnel,quote,chance)
              VALUES (OLD.username,OLD.username,OLD.customerID, (NOW()+ INTERVAL 14 DAY),(NOW()+ INTERVAL 14 DAY),'15','1','Post-Sales Follow-Up Alarm','Contact this customer for referrals and satisfaction survey',
              NOW(),'0','0.00',NULL)

    END;
    |
    DELIMITER ;

3 个答案:

答案 0 :(得分:2)

一个肯定可以想出一些花哨的算法,对我来说已经很晚了,所以我只是建议:

NOW() + INTERVAL CASE WEEKDAY(NOW() + INTERVAL 14 DAY) WHEN 5 THEN 13 WHEN 6 THEN 12 END DAY

以上是永远返回星期五。以下是周一总是返回:

NOW() + INTERVAL CASE WEEKDAY(NOW() + INTERVAL 14 DAY) WHEN 5 THEN 16 WHEN 6 THEN 15 END DAY

这里总是最接近:

NOW() + INTERVAL CASE WEEKDAY(NOW() + INTERVAL 14 DAY) WHEN 5 THEN 13 WHEN 6 THEN 15 END DAY

答案 1 :(得分:1)

你可以在now()函数上使用WEEKDAY()或DAYOFWEEK(), 这将在发生事件的一周中返回给您。

如果这一天是周末,你可以添加所需的天数。

答案 2 :(得分:0)

用户TaTa用他的答案触发了我的脑细胞,我想出了最终解决方案。我发布它作为帮助未来代码战士的答案,但我接受了TaTa的答案。:

DELIMITER |
CREATE TRIGGER Invoice_Funnel_AfterUpdate
    AFTER UPDATE ON INVOICE
    FOR EACH ROW BEGIN
    IF (OLD.status != NEW.status && NEW.status in ("1","5","7")
    THEN
      UPDATE customers
      SET set sales_funnel_status = '5', sales_funnel_status_date = NOW()
      WHERE customerID = OLD.customerID LIMIT 1 
      INSERT INTO alarms (username, createdBy, customerID, date_stamp, alert_stamp, minutes_before, active, subject, note,timestamp,funnel,quote,chance)
      VALUES (OLD.username,OLD.username,OLD.customerID, 
      IF(dayname(date(post_date)) = 'Saturday', (NOW()+ INTERVAL 16 DAY), NOW()),
      IF(dayname(date(post_date)) = 'Sunday', (NOW()+ INTERVAL 15 DAY), NOW()),
      IF(dayname(date(alert_stamp)) = 'Saturday', (NOW()+ INTERVAL 16 DAY), NOW()),
      IF(dayname(date(alert_stamp)) = 'Sunday', (NOW()+ INTERVAL 15 DAY), NOW()),
   '15','1','Post-Sales Follow-Up Alarm','Contact this customer for referrals and satisfaction survey',
      NOW(),'0','0.00',NULL)

END;
|
DELIMITER ;