How do you debug MySQL stored procedures?

后端 未结 16 1176
旧时难觅i
旧时难觅i 2020-11-30 17:44

My current process for debugging stored procedures is very simple. I create a table called \"debug\" where I insert variable values from the stored procedure as it runs. Thi

相关标签:
16条回答
  • 2020-11-30 18:09

    MySQL user defined variable (shared in session) could be used as logging output:

    DELIMITER ;;
    CREATE PROCEDURE Foo(tableName VARCHAR(128))
    BEGIN
      SET @stmt = CONCAT('SELECT * FROM ', tableName);
      PREPARE pStmt FROM @stmt;
      EXECUTE pStmt;
      DEALLOCATE PREPARE pStmt;
      -- uncomment after debugging to cleanup
      -- SET @stmt = null;
    END;;
    DELIMITER ;
    
    call Foo('foo');
    select @stmt;
    

    will output:

    SELECT * FROM foo
    
    0 讨论(0)
  • 2020-11-30 18:10

    I do something very similar to you.

    I'll usually include a DEBUG param that defaults to false and I can set to true at run time. Then wrap the debug statements into an "If DEBUG" block.

    I also use a logging table with many of my jobs so that I can review processes and timing. My Debug code gets output there as well. I include the calling param name, a brief description, row counts affected (if appropriate), a comments field and a time stamp.

    Good debugging tools is one of the sad failings of all SQL platforms.

    0 讨论(0)
  • 2020-11-30 18:10

    How to debug a MySQL stored procedure.

    Poor mans debugger:

    1. Create a table called logtable with two columns, id INT and log VARCHAR(255).

    2. Make the id column autoincrement.

    3. Use this procedure:

      delimiter //
      DROP PROCEDURE `log_msg`//
      CREATE PROCEDURE `log_msg`(msg VARCHAR(255))
      BEGIN
          insert into logtable select 0, msg;
      END
      
    4. Put this code anywhere you want to log a message to the table.

      call log_msg(concat('myvar is: ', myvar, ' and myvar2 is: ', myvar2));
      

    It's a nice quick and dirty little logger to figure out what is going on.

    0 讨论(0)
  • 2020-11-30 18:12

    Another way is presented here

    http://gilfster.blogspot.co.at/2006/03/debugging-stored-procedures-in-mysql.html

    with custom debug mySql procedures and logging tables.

    You can also just place a simple select in your code and see if it is executed.

    SELECT 'Message Text' AS `Title`; 
    

    I got this idea from

    http://forums.mysql.com/read.php?99,78155,78225#msg-78225

    Also somebody created a template for custom debug procedures on GitHub.

    See here

    http://www.bluegecko.net/mysql/debugging-stored-procedures/ https://github.com/CaptTofu/Stored-procedure-debugging-routines

    Was mentioned here

    How to catch any exception in triggers and store procedures for mysql?

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