user3562733
user3562733

Reputation: 35

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 ;

Upvotes: 0

Views: 1440

Answers (2)

knkarthick24
knkarthick24

Reputation: 3216

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 )

Upvotes: 0

Felix Pamittan
Felix Pamittan

Reputation: 31879

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
    )

Upvotes: 1

Related Questions