如何在SQL中每天一次执行触发器

时间:2018-11-28 02:52:53

标签: mysql sql mariadb

我们正在做一个关于微银行的项目,我们需要计算数据库级别的利率。因此,我们为此使用了过程和触发器。但是触发器需要每天执行一次才能执行以下给定的过程。您能否提供创建触发器的解决方案。预先感谢

DELIMITER //

create procedure addFDInterestToAccount(in account_number bigint(20))
BEGIN
declare interest float default 0;
declare account_type varchar(10);
declare rate float;
declare savings_account bigint(20);

start transaction;
select balance from fd_account where account_no = account_number into interest;
SELECT plan_id from fd_account where account_no = account_number into account_type;
SELECT saving_account_no from fd_account where account_no = account_number into savings_account;
select interest_rate from fd_plan where plan_id = account_type into rate;
set interest = interest*rate/1200;

insert into transaction (transaction_id, account_no, credit_debit, date_time, amount, type_, agent_id, is_fee)  values (null, savings_account, 'debit', now(), interest, 'not_special', null, false);
update account set balance = balance + interest where account_no = savings_account;
commit;
END //
DELIMITER ;

call addFDInterestToAccount(90842311);

2 个答案:

答案 0 :(得分:1)

据我了解您的要求,我认为您可以为此使用 SQL事件。通用语法如下:

 CREATE [OR REPLACE]
    [DEFINER = { user | CURRENT_USER | role | CURRENT_ROLE }]
    EVENT 
    [IF NOT EXISTS]
    event_name    
    ON SCHEDULE schedule
    [ON COMPLETION [NOT] PRESERVE]
    [ENABLE | DISABLE | DISABLE ON SLAVE]
    [COMMENT 'comment']
    DO sql_statement;

schedule:
    AT timestamp [+ INTERVAL interval] ...
  | EVERY interval 
    [STARTS timestamp [+ INTERVAL interval] ...] 
    [ENDS timestamp [+ INTERVAL interval] ...]

interval:
    quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |
              WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |
              DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}

您可以修改/使用以下代码来实现此目的,

 CREATE EVENT example
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_TIMESTAMP
DO call addFDInterestToAccount(90842311);

有关更多信息,请访问链接here

还要确保在运行事件之前先运行此查询

SET GLOBAL event_scheduler = ON;

答案 1 :(得分:0)

触发器定义为响应插入,更新或删除语句而运行的过程。每当您执行这些DML操作之一时,它将运行。您无法安排触发器每天运行一次。

来自MySql documentation(但适用于实现触发器的所有数据库):

  

定义触发器以在语句插入,更新或删除时激活   删除关联表中的行。这些行操作是触发器   事件。

相反,您需要查找任务计划程序。每个操作系统都有自己的操作系统,或者您可以找到第三方调度程序软件。