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

v440hwme  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(412)

我们正在做一个关于微型银行的项目,我们需要在数据库级别计算利率。所以我们使用了程序和触发器。但是触发器需要每天一次执行,以执行下面给定的过程。你能提供一个创建触发器的解决方案吗。提前谢谢

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);
wbgh16ku

wbgh16ku1#

触发器定义为响应insert、update或delete语句而运行的过程。它将在每次执行这些dml操作时运行。不能将触发器安排为每天运行一次。
来自mysql文档(但适用于实现触发器的所有数据库):
触发器定义为在语句插入、更新或删除关联表中的行时激活。这些行操作是触发事件。
相反,您需要寻找一个任务调度器。每个操作系统都有自己的或者你可以找到第三方的调度软件。

j0pj023g

j0pj023g2#

就我所了解的您的需求而言,我认为您可以使用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);

欲了解更多信息,请访问此处的链接
还要确保在运行事件之前运行此查询

SET GLOBAL event_scheduler = ON;

相关问题