Search code examples
mysqlsqlcursor

How to use cursors to update some columns according to another column?


I have a table called USER. This table has 2 columns as end_date, access_date. access_date is empty right now but i want to populate it like: if end_date exists : access_date = end_date + 1 year (anway i can make that operation) but my problem i could not construct the cursor i have not use cursor logic before.

i need something like:

    DELIMITER $$

    CREATE PROCEDURE user_procedure ()
    BEGIN

        DECLARE v_finished INTEGER DEFAULT 0;
        DECLARE v_user varchar(100) DEFAULT "";

        -- declare cursor for user
        DEClARE user_cursor CURSOR FOR
            SELECT * FROM USER;

        -- declare NOT FOUND handler
        DECLARE CONTINUE HANDLER
            FOR NOT FOUND SET v_finished = 1;

        OPEN user_cursor;

        get_user: LOOP

            FETCH user_cursor INTO v_user;

            IF v_finished = 1 THEN
                LEAVE get_user;
            END IF;

            -- operation
            -- something like:
 set @end_date = select from cursor
update expiry... etcs

        END LOOP get_user;

        CLOSE user_cursor;

    END$$

    DELIMITER ;

    CALL user_procedure();

but the problem i do not know how to define the cursor because as you see in example:

DECLARE v_user varchar(100) DEFAULT ""; i am pretty sure it is wrong and i try to fetch it into FETCH user_cursor INTO v_user;

So how can i properly define the cursor and fetch as a whole row and make change ?

Edit: some people did not understand and claimed i have asked same question again, ok i will edit the real code, now as below according to people's comment. This update must be applied to each individual row.

set @key = 'bla bla';

    delimiter $$
    create procedure select_or_insert()
    begin
        IF EXISTS (select USER_EXPIRY_DATE from USER) THEN
            update USER set ACCESS_EXPIRY_DATE = DATE_ADD(USER_EXPIRY_DATE, INTERVAL 1 YEAR);
        ELSE IF EXISTS (select USER_START_DATE from USER) THEN
            SET @start_date = (select USER_START_DATE from USER);
            SET @start_date_to_be_added = aes_decrypt(@start_date,@key)
          update USER set ACCESS_EXPIRY_DATE = DATE_ADD(USER_EXPIRY_DATE, INTERVAL 1 YEAR);
        END IF;
    end $$
    delimiter ;

but in here for example:

ELSE IF EXISTS (select USER_START_DATE from USER) is returning more than 1 row.


Solution

  • You don't need a cursor for that, you can simply use an update statement:

    UPDATE User
    SET access_date = DATE_ADD(end_date, INTERVAL 1 YEAR)
    WHERE end_date IS NOT NULL