Debugging MySQL Triggers - mysql

I love triggers for one reason - they just work. I hate triggers for one reason - when they don't work, forget about trying to debug. O the sweet frustration.
Basically, I want to see THE update, delete, insert, etc query that was ran. I want to see that query ... somewhere, in my terminal or a log, exactly how and when MySQL executes it, and possibly any corresponding output/errors. Thoughts/hacks?
I'm trying to debug an update query with a few joins and what not. My queries are much more complex but for brevity here's an example.
DELIMITER |
CREATE TRIGGER ireallyhateyourightnow AFTER UPDATE ON watch_this_table
FOR EACH ROW BEGIN
IF (OLD.my_value != NEW.my_value) THEN
update
my_table
set
my_column = NEW.my_value;
END IF;
END|
DELIMITER ;
Here is some additional context that may help influence a suggestion or answer. Again, I'm less interested in semantics/syntax and more interested in seeing MySQL run the query but by all means, I'm open to anything at this point.
Strace does not work/show query.
Non-replicated environment BUT if the bin logs show trigger statements I will certainly set this up.
Does "show full processlist" show trigger execution and/or statements executed within (I never see them after running show full processlist as fast as perl can run it but I might just be missing it)?
General query log does not show these queries (certainly not the error log).
I'm not using aliases (anymore).
No syntax errors when creating the trigger.
The IF statement works.
When I insert the NEW values into a "test/temp" table and manually run the update query it works (I've even went so far as to actually inserting the whole update query)
I can't show you the query but as I just mentioned, it works when I run manually if that helps.
I've removed all erroneous characters, tabs, carriage returns, newlines, etc.
The MySQL socket would only show local connection/data but not MySQL internal workings, I think.
MyISAM so INNODB logs aren't an option
lsof didn't seem to show anything else to be of use.
I'm using MySQL 5.0.77 on CentOS 5.5.

There's an alternate way of testing it by having a temporary debug table. In the example here, they create it in an own debug database.
Step 1: Create a table
DROP TABLE IF EXISTS debug;
CREATE TABLE debug (
proc_id varchar(100) default NULL,
debug_output text,
line_id int(11) NOT NULL auto_increment,
PRIMARY KEY (line_id)
)
Step 2: Create debug SPs to fill the debug table
DELIMITER $$
DROP PROCEDURE IF EXISTS `debug_insert` $$
CREATE PROCEDURE `debug_insert`(in p_proc_id varchar(100),in p_debug_info text)
begin
insert into debug (proc_id,debug_output)
values (p_proc_id,p_debug_info);
end $$
DROP PROCEDURE IF EXISTS `debug_on` $$
CREATE PROCEDURE `debug_on`(in p_proc_id varchar(100))
begin
call debug_insert(p_proc_id,concat('Debug Started :',now()));
end $$
DROP PROCEDURE IF EXISTS `debug_off` $$
CREATE PROCEDURE `debug_off`(in p_proc_id varchar(100))
begin
call debug_insert(p_proc_id,concat('Debug Ended :',now()));
select debug_output from debug where proc_id = p_proc_id order by line_id;
delete from debug where proc_id = p_proc_id;
end $$
Step 3: Invoke the debug SPs in your trigger
Like this,
CREATE PROCEDURE test_debug()
begin
declare l_proc_id varchar(100) default 'test_debug';
call debug_on(l_proc_id);
call debug_insert(l_proc_id,'Testing Debug');
call debug_off(l_proc_id);
end $$
As a result the debug table would be filled as follows,
+------------------------------------+
| debug_output |
+------------------------------------+
| Debug Started :2006-03-24 16:10:33 |
| Testing Debug |
| Debug Ended :2006-03-24 16:10:33 |
+------------------------------------+

You can debug triggers using dbForge Studio for MySQL. Try trial version.
There is a detailed description of the trigger debugging process in the documentation: Debugging \ Debugging Stored Routines \ How To: Start Trigger Debugging.

MYSQL PROCEDURE => incron => tail -f 'mysql_dynamic.log'
A Stored Procedure can be invoked inside a trigger but must return nothing
CREATE PROCEDURE `DYN_LOG` (IN s VARCHAR(500))
BEGIN
SELECT s into outfile '/var/spool/incron/mysql_dynamic_spool/foo_file';
DO SLEEP(.1); // create a gap beetween multiple shuts
END
Now anywhere in a trigger you can invoke
CREATE TRIGGER `trig_name` BEFORE UPDATE ON `tb_name`
FOR EACH ROW
BEGIN
CALL DYN_LOG(concat_ws('\t',NEW.col1,NEW.col2));
...
// rest of the code
END
for Linux machines apt-get install incron (debian incron tutorial)
Create the folder in which mysql will inject foo_file
mkdir -m 777 /var/spool/incron/mysql_dynamic_spool
incrontab -e
and add following incron job
/var/spool/incron/mysql_dynamic_spool IN_CREATE /path/foo_file_procesor $#/$#
Create executable script "/path/foo_file_procesor"
#!/bin/sh
# // $1 is the foo_file absolute addres
body="$(cat $1)" #// read file content
rm $1
log=/var/log/mysql_dynamic.log #// message collector
echo "`date "+%Y-%m-%d %H:%M:%S"`\t== dyn_log ==\t$body">>$log
exit 0
Now watch the collector file
tail -f /var/log/mysql_dynamic.log

Related

How to write stored procedures in Wampserver to run Automatically

I didn't know anything about Stored procedures. unfortunately I have to run a stored procedure automatically.
I have a table called pass and I want to update status as cancelled at the end of the day automatically. I'm using phpmyadmin in wampserver.
I have already tried some codes but I don't know this code is correct and how to set execution automatically.
here is my code,
CREATE PROCEDURE MyTask
AS
BEGIN
SET NOCOUNT ON;
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- For executing the stored procedure at 1:00 A.M
declare #delayTime nvarchar(50)
set #delayTime = '01:00'
while 1 = 1
BEGIN
waitfor time #delayTime
BEGIN
ALTER PROCEDURE [dbo].[updateDuration] AS
UPDATE pass SET status = 'Cancelled' WHERE duration_type='Daily' && duration = DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY);
--Name for the stored proceduce you want to call on regular bases
execute [gatepass].[dbo].[updateDuration];
END
END
END
It says that to put below code, but I don't know where to put these.
-- Sets stored procedure for automatic execution.
sp_procoption #ProcName = 'MyTask',
#OptionName = 'startup',
#OptionValue = 'on'
Method #1 - Batching
Create a script named runMyTask.sql or whatever you want.
That script should have your SQL to run the stored procedure:
-- Sets stored procedure for automatic execution.
CALL sp_procoption('MyTask','startup', 'on');
Then you need a batch script which you might name runMyTask.bat.
In the .bat file you add the line that runs the mysql.exe command line tool and redirects the contents of the runMyTask.sql file along the lines of something like
C:/wamp/bin/mysql/mysql..../bin/mysql -u root --password=your_password database_name < C:/path/to/runMyTask.sql
When you have tested that the batch script runs correctly from the windows cmd shell, set it up in the scheduler.
Method #2 MySQL - Event Scheduler
To use the event scheduler you'll need to first make sure you it's enabled on the server. By default it is not. From the aforementioned mysql command line, login as root.
SET GLOBAL event_scheduler = ON;
After you turn it on, run a SHOW PROCESSLIST; command and you should see a line similar to this one, showing the user event_scheduler owning a process.
| 10729276 | event_scheduler | localhost | NULL | Daemon | 4 | Waiting on empty queue | NULL | 0.000 |
At this point you can add "events". To add your stored procedure run as an event, once an hour:
USE your_db;
CREATE EVENT IF NOT EXISTS EventRunMyTask
ON SCHEDULE EVERY 1 HOUR
ENABLE
DO CALL sp_procoption('MyTask','startup', 'on');
If everything goes well you should be able to see information about the scheduled job using SHOW EVENTS;

Can I neatly skip all or part of a mySQL script (esp that contains creation of stored procedures)?

I have a mySQL script, that I have to execute, but for a bunch of useless reasons (and more importantly boring), I might want it to skip most of that script.
Let's say before each part of the script I want to check select okToRun from options returns true before running the script.
So my script looks something like this
DELIMITER $$
DROP PROCEDURE IF EXISTS procedure1$$
CREATE PROCEDURE procedure1()
BEGIN
IF (select okToRun from options) THEN
... -- do some stuff
END IF;
END$$
CALL procedure1()$$
DROP PROCEDURE IF EXISTS procedure2$$
CREATE PROCEDURE procedure2()
BEGIN
IF (select okToRun from options) THEN
... -- do some other stuff
END IF;
END$$
DROP PROCEDURE IF EXISTS procedure3$$
CREATE PROCEDURE procedure3()
BEGIN
IF (select okToRun from options) THEN
... -- do even more stuff!
END IF;
END$$
CALL procedure2()$$
CALL procedure3()$$
I hate repeated code, so how can I put the check right at the start of the script, rather than having to keep repeating myself?
I thought I'd be clever and wrap the whole thing in one stored procedure and do my if statement there... but you can't really create a stored procedure within another. And I need to keep the other stuff within their own stored procedures.
I also realise it'd be better to do the check before executing the script at all, but, well, I can't ;)
If the answer simply is that I can't do this, fair enough. But I want to be sure before repeating code like a big fat heathen.
The MySQL client script syntax does not support conditionals or loops or other programming logic.
The best idea I could come up with is to use prepared statements, but unfortunately CREATE PROCEDURE is not supported in this manner.
SET #do_create := true;
SET #create_proc1 := IF(#do_create, 'CREATE PROCEDURE ...', 'DO 1');
PREPARE stmt FROM #create_proc1
I got this error:
ERROR 1295 (HY000): This command is not supported in the prepared statement protocol yet
The list of commands supported in this way is documented here: http://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
In MySQL 5.7, they introduced a new client shell called mysqlsh that is supposed to support a more featureful scripting environment, allowing you to write Python code and so on. I haven't tried this tool yet.
But you could do the same thing by writing your own script in Python or any other language you want. Then you can code the conditional logic to create procedures or whatever. That's your best bet.

If conditional in SQL Script for Mysql

In a sql script that does sequential execution, is there a way one can introduce an IF THEN ELSE conditional to control the flow of query execution?
I happened to run into this http://www.bennadel.com/blog/1340-MySQL-Does-Not-Support-IF-ELSE-Statements-In-General-SQL-Work-Flow.htm
which says that the IF THEN ELSE will not work in a sql script.
Is there another way around?
Basically, I want to run a particular "select colName from table" command and check if colName corresponds to a particular value. If it does, proceed with the rest of the script. Else, halt execution.
Please advise.
I just wrap my SQL script in a procedure, where conditional code is allowed. If you'd rather not leave the statements lying around, you can drop the procedure when you're done. Here's an example:
delimiter //
create procedure insert_games()
begin
set #platform_id := (select id from platform where name = 'Nintendo DS');
-- Only insert rows if the platform was found
if #platform_id is not null then
insert into game(name, platform_id) values('New Super Mario Bros', #platform_id);
insert into game(name, platform_id) values('Mario Kart DS', #platform_id);
end if;
end;
//
delimiter ;
-- Execute the procedure
call insert_games();
-- Drop the procedure
drop procedure insert_games;
If you haven't used procedures, the "delimiter" keyword might need some explanation. The first line switches the delimiter to "//" so that we can include semi-colons in our procedure definition without MySQL attempting to interpret them yet. Once the procedure has been created, we switch the delimiter back to ";" so we can execute statements as usual.
After doing some research I think I may have found a way to work around this. I was looking for a way to verify if a script had already executed against a target database. This will be primarily for version control of my databases. I have a table created to keep track of the scripts that have been executed and wanted some flow inside my scripts to check that table first before execution. While I have not completely solved the problem yet I have created a simple script that basically does what I need, I just need to wrap the DDL into the selects based on the value of the variables.
step 1 - Setup a bit variable to hold the result
step 2 - do your select and set the variable if the result is found
step 3 - Do what you need to do on false result
step 4 - Do what you need to do on true result
Here is the example script
set #schemachangeid = 0;
select #schemachangeid := 1 from SchemaChangeLog where scriptname = '1_create_tables.sql';
select 'scriptalreadyran' from dual where #schemachangeid = 1;
select 'scriptnotran' from dual where #schemachangeid = 0;
I also recognize this is an old thread but maybe this will help someone out there trying to do this kind of thing outside of a stored procedure like me.

MySQL query browser procedure error code -1

I'm having a rather strange problem with MySQL. Trying to create a procedure to update some fields in the database (the code is below).
The problem is with the line that is currently commented. It seems that if no SELECT statements get executed during the procedure MySQL query browser will return an error code of "-1, error executing SQL query".
I tried the same thing in HeidiSQL and the error was "cannot return result set". So I suppose the question is do I always have to select something in the procedure, or is there some other thing I missed.
The query works fine when the comment is removed.
DELIMITER /
DROP PROCEDURE IF EXISTS updateFavourites /
CREATE PROCEDURE updateFavourites(quota INT)
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE artist_id,releases INT;
DECLARE c_artist Cursor FOR
SELECT Artist.id_number,COUNT(Artist.id_number) FROM Artist
JOIN CD ON CD.is_fronted_by = Artist.id_number
GROUP BY Artist.id_number;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000'
SET done=1;
IF quota > 0 THEN
OPEN c_artist;
REPEAT
FETCH c_artist INTO artist_id,releases;
IF NOT done THEN
IF releases >= quota THEN
UPDATE CD SET CD.rating='favourite' WHERE CD.is_fronted_by = artist_id;
END IF;
END IF;
UNTIL done END REPEAT;
CLOSE c_artist;
-- SELECT 'Great success';
ELSE
SELECT CONCAT('\'quota\' must be greater than 0.',' Got (',quota,')');
END IF;
END /
DELIMITER ;
Here's the sql to create the tables and some data:
DROP TABLE IF EXISTS CD;
DROP TABLE IF EXISTS Artist;
CREATE TABLE Artist (
id_number INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
);
CREATE TABLE CD (
catalog_no INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY,
is_fronted_by INT UNSIGNED,
rating ENUM ('favourite','top draw','good','so-so','poor','rubbish'),
CONSTRAINT fk_CD_Artist FOREIGN KEY (is_fronted_by) REFERENCES Artist(id_number) ON UPDATE CASCADE
);
INSERT INTO Artist VALUES(11,'Artist 1');
INSERT INTO Artist VALUES(10,'Artist 2');
INSERT INTO CD VALUES (7,11, 'top draw');
INSERT INTO CD VALUES (650,11,'good');
INSERT INTO CD VALUES (651,11,'good');
INSERT INTO CD VALUES (11,10,'favourite');
Query Browser is not for running scripts, just single query.
I tried your code by moving cursor into each query (except DELIMITER) and pressing Ctrl+Enter.
It created that stored procedure without problem. (just refresh schema on the left).
If you wish creating procedure, use menu "Script"->"Create stored procedure/function".
But better forget about QueryBrowser it is not supported at all (and actunally not useful).
If you have decent hardware and plenty resources, try Workbench 5.2 otherwise use SQLyog
Googling around, there are several reports of the same error, but little information to solve the problem. There's even a bug logged at mysql.com but it appears to have been abandoned without being resolved.
There's another StackOverflow question on the same error, but it's also unresolved.
All it means is that there is no result set from the query. Looking at the source code, it appears that sometimes an error status of MYX_SQL_ERROR is set when the query has no result set. Perhaps this is not an appropriate consequence?
I notice that when I use the mysql command-line client, it yields no error for calling a proc that returns no result set.
update: I tried to revive that MySQL bug report, and provide a good test case for them. They changed the bug from "no feedback" to "verified" -- so at least they acknowledge it's a bug in Query Browser:
[11 Dec 9:18] Sveta Smirnova
Bill,
thank you for the feedback. Verified
as described.
Although most likely this only be
fixed when MySQL Query Browser
functionality is part of MySQL
workbench.
I guess the workaround is to ignore the -1 error, or to test your stored procedures in the command-line mysql client, where the error does not occur.
The comment supposes the issue will disappear as the Query Browser functionality becomes part of MySQL Workbench. This is supposed to happen in MySQL Workbench 5.2. I'll download this beta and give it a try.
MySQL Workbench 5.2 is in Beta, but I would assume MySQL engineering can't predict when the Beta will become GA. Those kinds of predictions are hard enough under standard conditions, but there's a lot of extra uncertainty of MySQL's fate due to the unresolved Oracle acquisition.
update: Okay, I have tried MySQL Workbench 5.2.10 beta. I executed a stored procedure like this:
CREATE PROCEDURE FooProc(doquery SMALLINT)
BEGIN
IF doquery THEN
SELECT * FROM Foo;
END IF;
END
When I CALL FooProc(0) the response is no result set, and the status is simply "OK".
When I CALL FooProc(1) the response is the result of SELECT * FROM Foo as expected.
However, there's another bug related to calling procedures. Procedures may have multiple result sets, so it's hard to know when to close the statement when you execute a CALL query. The consequence is that MySQL Workbench 5.2 doesn't close the statement, and if you try to do another query (either CALL or SELECT) it gives you an error:
Commands out of sync; you can't run this command now.
MySQL doesn't support multiple concurrent open queries. So the last one must be closed before you can start a new one. But it isn't closing the CALL query. This bug is also logged at the MySQL site.
The bug about commands out of sync has been resolved. They say it's fixed in MySQL Workbench 5.2.11.
Try putting BEGIN and END blocks around the multiple statements in the IF block as such:
IF quota > 0 THEN
BEGIN
OPEN c_artist;
REPEAT
FETCH c_artist INTO artist_id,releases;
IF NOT done THEN
IF releases >= quota THEN
UPDATE CD SET CD.rating='favourite' WHERE CD.is_fronted_by = artist_id;
END IF;
END IF;
UNTIL done END REPEAT;
CLOSE c_artist;
END;
ELSE
SELECT CONCAT('\'quota\' must be greater than 0.',' Got (',quota,')');
END IF;

How do you debug MySQL stored procedures?

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. This allows me to see the value of any variable at a given point in the script, but is there a better way to debug MySQL stored procedures?
The following debug_msg procedure can be called to simply output a debug message to the console:
DELIMITER $$
DROP PROCEDURE IF EXISTS `debug_msg`$$
DROP PROCEDURE IF EXISTS `test_procedure`$$
CREATE PROCEDURE debug_msg(enabled INTEGER, msg VARCHAR(255))
BEGIN
IF enabled THEN
select concat('** ', msg) AS '** DEBUG:';
END IF;
END $$
CREATE PROCEDURE test_procedure(arg1 INTEGER, arg2 INTEGER)
BEGIN
SET #enabled = TRUE;
call debug_msg(#enabled, 'my first debug message');
call debug_msg(#enabled, (select concat_ws('','arg1:', arg1)));
call debug_msg(TRUE, 'This message always shows up');
call debug_msg(FALSE, 'This message will never show up');
END $$
DELIMITER ;
Then run the test like this:
CALL test_procedure(1,2)
It will result in the following output:
** DEBUG:
** my first debug message
** DEBUG:
** arg1:1
** DEBUG:
** This message always shows up
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.
How to debug a MySQL stored procedure.
Poor mans debugger:
Create a table called logtable with two columns, id INT and log VARCHAR(255).
Make the id column autoincrement.
Use this procedure:
delimiter //
DROP PROCEDURE `log_msg`//
CREATE PROCEDURE `log_msg`(msg VARCHAR(255))
BEGIN
insert into logtable select 0, msg;
END
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.
Yes, there is a specialized tools for this kind of thing - MySQL Debugger.
There are GUI tools for debugging stored procedures / functions and scripts in MySQL. A decent tool that dbForge Studio for MySQL, has rich functionality and stability.
Debugger for mysql was good but its not free. This is what i use now:
DELIMITER GO$
DROP PROCEDURE IF EXISTS resetLog
GO$
Create Procedure resetLog()
BEGIN
create table if not exists log (ts timestamp default current_timestamp, msg varchar(2048)) engine = myisam;
truncate table log;
END;
GO$
DROP PROCEDURE IF EXISTS doLog
GO$
Create Procedure doLog(in logMsg nvarchar(2048))
BEGIN
insert into log (msg) values(logMsg);
END;
GO$
Usage in stored procedure:
call dolog(concat_ws(': ','#simple_term_taxonomy_id', #simple_term_taxonomy_id));
usage of stored procedure:
call resetLog ();
call stored_proc();
select * from log;
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?
I'm late to the party, but brought more beer:
http://ocelot.ca/blog/blog/2015/03/02/the-ocelotgui-debugger/
and
https://github.com/ocelot-inc/ocelotgui
I tried, and it seems pretty stable, supporting Breakpoints and Variable inspection.
It's not a complete suite (just 4,1 Mb) but helped me a lot!
How it works:
It integrates with your mysql client (I'm using Ubuntu 14.04), and after you execute:
$install
$setup yourFunctionName
It installs a new database at your server, that control the debugging process. So:
$debug yourFunctionName('yourParameter')
will give you a chance to step by step walk your code, and "refreshing" your variables you can better view what is going on inside your code.
Important Tip: while debugging, maybe you will change (re-create the procedure). After a re-creation, execute: $exit and $setup before a new $debug
This is an alternative to "insert" and "log" methods.
Your code remains free of additional "debug" instructions.
Screenshot:
I just simply place select statements in key areas of the stored procedure to check on current status of data sets, and then comment them out (--select...) or remove them before production.
MySQL Connector/Net 6.6 has a feature to Debug Stored Procedures and Functions
Installing the Debugger
To enable the stored procedure debugger:
For Connector/Net 6.6: Install Connector/Net 6.6 and choose the Complete option.
For Connector/Net 6.7 and later: Install the product MySQL for Visual Studio, to which the stored procedure debugger belongs.
Starting the Debugger
To start the debugger, follow these steps:
Choose a connection in the Visual Studio Server Explorer.
Expand the Stored Procedures folder. Only stored procedures can be debugged directly. To debug a user-defined function, create a stored
procedure that calls the function.
Click on a stored procedure node, then right-click and from the context menu choose Debug Routine.
MySql Connector/NET also includes a stored procedure debugger integrated in visual studio as of version 6.6,
You can get the installer and the source here:
http://dev.mysql.com/downloads/connector/net/
Some documentation / screenshots:
https://dev.mysql.com/doc/visual-studio/en/visual-studio-debugger.html
You can follow the annoucements here:
http://forums.mysql.com/read.php?38,561817,561817#msg-561817
UPDATE: The MySql for Visual Studio was split from Connector/NET into a separate product, you can pick it (including the debugger) from here https://dev.mysql.com/downloads/windows/visualstudio/1.2.html (still free & open source).
DISCLAIMER: I was the developer who authored the Stored procedures debugger engine for MySQL for Visual Studio product.
The first and stable debugger for MySQL is in dbForge Studio for MySQL
I had use two different tools to debug procedures and functions:
dbForge - many functional mysql GUI.
MyDebugger - specialized tool for debugging ... handy tool for debugging.vote http://tinyurl.com/voteimg
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
Toad mysql. There is a freeware version
http://www.quest.com/toad-for-mysql/
Answer corresponding to this by #Brad Parks
Not sure about the MySQL version, but mine was 5.6, hence a little bit tweaking works:
I created a function debug_msg which is function (not procedure) and returns text(no character limit) and then call the function as SELECT debug_msg(params) AS my_res_set, code as below:
CREATE DEFINER=`root`#`localhost` FUNCTION `debug_msg`(`enabled` INT(11), `msg` TEXT) RETURNS text CHARSET latin1
READS SQL DATA
BEGIN
IF enabled=1 THEN
return concat('** DEBUG:', "** ", msg);
END IF;
END
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `proc_func_call`(
IN RegionID VARCHAR(20),
IN RepCurrency INT(11),
IN MGID INT(11),
IN VNC VARCHAR(255)
)
BEGIN
SET #enabled = TRUE;
SET #mainQuery = "SELECT * FROM Users u";
SELECT `debug_msg`(#enabled, #mainQuery) AS `debug_msg1`;
SET #lastQuery = CONCAT(#mainQuery, " WHERE u.age>30);
SELECT `debug_msg`(#enabled, #lastQuery) AS `debug_msg2`;
END $$
DELIMITER