如何用select查询创建临时表更新它并将其插入mysql?

时间:2017-02-24 13:17:09

标签: mysql stored-procedures temp-tables

任何人都可以告诉我为什么这不起作用

Create Procedure LeaveUpdate()
Begin
CREATE TEMPORARY TABLE leavebal AS (SELECT * FROM tbl_leave_balance WHERE month = month(DATE_SUB(now(), INTERVAL 1 MONTH)) and year = year(DATE_SUB(now(), INTERVAL 1 MONTH)));
UPDATE leavebal SET leave_balance = 0 WHERE leave_balance < 0;
UPDATE leavebal  SET month = month(now()), year = year(now()), leaves_taken = 0, carry_forward = leave_balance, comp_off = 0;
UPDATE leavebal SET total_leaves = carry_forward + leaves_allowed + comp_off, leave_balance = carry_forward + leaves_allowed + comp_off;
INSERT INTO tbl_leave_balance (emp_id, month, year, carry_forward, leaves_allowed, comp_off, total_leaves, leaves_taken, leave_balance)
SELECT emp_id, month, year, carry_forward, leaves_allowed, comp_off, total_leaves, leaves_taken, leave_balance FROM leavebal;
End

1 个答案:

答案 0 :(得分:0)

您必须使用delimiter,试试这个:

DELIMITER $$

    DROP PROCEDURE IF EXISTS `LeaveUpdate` $$
Create Procedure LeaveUpdate()
Begin
CREATE TEMPORARY TABLE leavebal AS (SELECT * FROM tbl_leave_balance WHERE month = month(DATE_SUB(now(), INTERVAL 1 MONTH)) and year = year(DATE_SUB(now(), INTERVAL 1 MONTH)));
UPDATE leavebal SET leave_balance = 0 WHERE leave_balance < 0;
UPDATE leavebal  SET month = month(now()), year = year(now()), leaves_taken = 0, carry_forward = leave_balance, comp_off = 0;
UPDATE leavebal SET total_leaves = carry_forward + leaves_allowed + comp_off, leave_balance = carry_forward + leaves_allowed + comp_off;
INSERT INTO tbl_leave_balance (emp_id, month, year, carry_forward, leaves_allowed, comp_off, total_leaves, leaves_taken, leave_balance)
SELECT emp_id, month, year, carry_forward, leaves_allowed, comp_off, total_leaves, leaves_taken, leave_balance FROM leavebal;
End$$

    DELIMITER ;