用于在每月2日创建发票的MySQL触发器

cwxwcias  于 2022-12-03  发布在  Mysql
关注(0)|答案(1)|浏览(97)

因此,我有两个表,一个是Invoice,另一个是invPerConn(每个连接的发票)。invoice表需要一个触发器,用于在下个月的每2日插入一个新发票,并添加一个新的到期日或相应月份的5日。插入操作发生时,触发器需要将invPerConn中的“line_price”插入发票“amount_due_left”中,并将invPerConn中的“过期_费用”插入发票

create table invoice(
invoice_id DECIMAL(3),
invoice_date DATE,
due_date DATE,
overdue_fee DECIMAL(10,2),
amt_due_left decimal(12,2),
PRIMARY KEY(invoice_id));

INSERT INTO invoice VALUES 
(1,'2020-11-02','2020-11-05',15,120.24),
(2,'2020-11-02','2020-11-05',35,200.00),
(3,'2020-11-02','2020-11-05',150,1300.00),
(4,'2020-11-02','2020-11-05',120,1200.00);

create table invPerConn(
cust_connection int,
invoice_id  DECIMAL(3),
line_price decimal(12,2),
overdue_fee DECIMAL(10,2),
CONSTRAINT fk_has_custConnection FOREIGN KEY(cust_connection)
        REFERENCES custConnection(cust_connection),
CONSTRAINT fk_has_invoice FOREIGN KEY(invoice_id)
        REFERENCES invoice(invoice_id));
    

insert into invPerConn values
(1,1,15,120.24),
(2,2,35,200.00),
(3,3,150,1300.00),
(4,4,120,1300.00);

我真的不知道从哪里开始,我从来没有使用过生成日期的触发器。

2izufjch

2izufjch1#

CREATE TRIGGER insert_invoice
AFTER INSERT ON invPerConn
FOR EACH ROW
BEGIN
    -- Calculate the next month's 2nd day
    DECLARE next_month_date DATE = DATEADD(MONTH, 1, CURRENT_DATE);
    SET next_month_date = DATEADD(DAY, 1, next_month_date);

    -- Calculate the next month's 5th day
    DECLARE next_month_due_date DATE = DATEADD(MONTH, 1, CURRENT_DATE);
    SET next_month_due_date = DATEADD(DAY, 4, next_month_due_date);

    -- Insert a new invoice for the next month with the calculated dates
    INSERT INTO invoice (invoice_id, invoice_date, due_date, overdue_fee, amt_due_left)
    VALUES (NEW.invoice_id, next_month_date, next_month_due_date, NEW.overdue_fee, NEW.line_price);
END;

此触发器使用DATEADD函数计算下个月得第2天与第5天,然后在invoice表中插入一个新行,其中包含这些日期以及invPerConn表中得overdue_feeline_price值.
您可以修改此触发器以满足您的特定要求,如插入具有不同值集的新发票,或使用不同的触发器事件(例如,使用AFTER UPDATE而不是AFTER INSERT)。您还可以向触发器添加附加逻辑,以处理可能出现的任何错误或例外情况。

相关问题