MySql Cursor - Creating a procedure

后端 未结 3 790
温柔的废话
温柔的废话 2021-01-06 00:12

i\'m trying to create a cursor for the first time. I have looked at the documentation, i understand the concept, but i can\'t seem to get it to even be declared...

I

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-06 00:57

    I needed to do the same thing, so I ended-up writing a stored procedure to do the job. I've included it here and it runs great on MySQL Workbench. Interestingly it will not run correctly on Navicat as the original select statement won't omit the NULL values and would, therefore, delete all of your indexes.

    I recommend that you read through the code and break a few things out and run them separately so that you are sure it will do what you want.

    The way this is written, it should delete every foreign key in all of your databases in a given connection. Don't run it the way it is unless that's what you want to do.

    Use at your own risk.

    DELIMITER $$
    
    CREATE PROCEDURE `pRemoveAllForeignKeys`()
    BEGIN
    
    DECLARE sName TEXT;
    DECLARE cName TEXT;
    DECLARE tName TEXT;
    DECLARE done INT DEFAULT 0;
    DECLARE cur CURSOR FOR 
        SELECT TABLE_SCHEMA, CONSTRAINT_NAME, TABLE_NAME
            FROM information_schema.key_column_usage
            WHERE REFERENCED_TABLE_SCHEMA IS NOT NULL
    --          AND TABLE_SCHEMA = 'NameOfAParticularSchema' -- use this line to limit the results to one schema
    --          LIMIT 1 -- use this the first time because it might make you nervous to run it all at once.
            ;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
    
    OPEN cur;
    read_loop: LOOP 
    FETCH cur INTO sName, cName, tName;
        IF done THEN
            LEAVE read_loop;
        END IF;
        SET @s = CONCAT('ALTER TABLE ',sName, '.', tName, ' DROP FOREIGN KEY ', cName);
    --      SELECT @s; -- uncomment this if you want to see the command being sent
        PREPARE stmt FROM @s;
        EXECUTE stmt;
    END LOOP;
    CLOSE cur;
    deallocate prepare stmt;
    END
    

提交回复
热议问题