MySql Cursor - Creating a procedure

后端 未结 3 788
温柔的废话
温柔的废话 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:50
    create or replace procedure cursor_sample()
    BEGIN
    
    DECLARE done int default 0 ;
    DECLARE data1 varchar(20) ;
    DECLARE data2 int ;
    
    DECLARE cur1 CURSOR FOR 
    select sname,examscore from student ;
    DECLARE CONTINUE HANDLER 
    FOR NOT FOUND SET done = 1 ;
    OPEN cur1;
    loop1:LOOP 
        FETCH cur1 into data1,data2 ;
        insert into student_log(user_name,score) values (data1,data2) ;
        if done = 1 THEN
            LEAVE loop1 ;
        END IF ;
    END LOOP;
    CLOSE cur1;
    END ;
    //
    

    --This is an example for a Proper Cursor implementation inside a Stored Procedure.---

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-06 01:07

    You forget to reset the delimiter to NOT ;

    delimiter ##
    ...
    end##
    

    need to put a space right after delimiter

    And the ending END does not require ;

    0 讨论(0)
提交回复
热议问题