简体   繁体   中英

MySQL Stored Procedure Select Check Insert

So I'm trying to create a stored procedure in MySQL version 5.5. I'm not sure what is wrong but what I want to accomplish is.

Get record From Table-A that over 7 days old. And then insert into Table-B, but I need to check if it is exist in Table B. If it is exists then skip, else Insert it.

So here is my code:

DROP PROCEDURE IF EXISTS `move_record`;
DELIMITER //
CREATE PROCEDURE `move_record`()
BEGIN
        DECLARE done INT DEFAULT FALSE;
        DECLARE dt DATETIME;
        DECLARE uid,value BIGINT(20);
        DECLARE category VARCHAR(30);
        DECLARE data,comments VARCHAR(255);
        DECLARE cancel TINYINT(1) DEFAULT NULL;

        DECLARE curs CURSOR FOR SELECT `datetime`,user_id,category,data,comments,cancel FROM `record` WHERE `datetime` < DATE_SUB(CURDATE(), INTERVAL 7 DAY);

        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

        OPEN curs;

        myloop: LOOP
        FETCH NEXT FROM curs INTO dt,uid,category,data,comments,cancel;
        IF done THEN
            LEAVE myloop;
        END IF;

        IF NOT EXISTS (SELECT * FROM `record_arc`
                        WHERE record_arc.`datetime` = dt
                        AND record.user_id = uid )
        INSERT INTO `record_arc` (`datetime`,user_id,category,data,comments,cancel) VALUES (dt,uid,category,data,comments,cancel);

        END IF;
        END LOOP myloop;

        CLOSE curs;
        DEALLOCATE curs;
END//
DELIMITER ;

Maybe you can do this without a loop.

INSERT INTO `record_arc`(
    `datetime`,
    user_id,
    category,
    data,
    comments,
    cancel
)
SELECT 
    `datetime`,
    user_id,
    category,
    data,
    comments,
    cancel 
FROM `record` r
WHERE 
    `datetime` < DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    AND NOT EXISTS(
        SELECT 1
        FROM `record_arc` r2
        WHERE
            r2.`datetime` = r.`datetime`
            AND r2.user_id = r.user_id
    )

Alias name you used it wrongly. Check the below code

IF NOT EXISTS (SELECT 1 FROM `record_arc`
                            WHERE record_arc.`datetime` = dt
                            AND record_arc.user_id = uid )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM