Can a stored procedure plus a sql query be executed from within a trigger?
procedure plus query
SET #tmp = (SELECT fvalue FROM ftable WHERE id=2);
SET #SQL = CONCAT('INSERT INTO ',#tmp,' VALUES (''buhambug'')');
PREPARE stmt FROM #SQL;
EXECUTE stmt;
If so what are the rules and links to examples? I have't been able to find any.
Yeah, you can call a stored procedure from a trigger like this:
Create trigger foo after insert on table for each row
BEGIN
call your_procedure(params);
END$$
Note the ending delimiter. If ; is the default delimiter inside the trigger as well, then it won't work, for MySQL will treat each command separately and throw error. You want the entire code inside the trigger to be executed together. hence declare a different delimiter, like $$ prior to defining the trigger, through Delimiter $$. Then, ; will work correctly inside the the trigger. After you terminate the trigger through $$, don't forget to restore the default delimiter.
Related
I am trying to understand, why delimiter used with stored procedure in mysql?
but i couldn't.
DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;`
Mysql's default delimiter is ; which is used for one statement in the command line , something as
select * from users ;
When you write a trigger or stored procedure to execute the entire code mysql needs to understand that its a block of code/query.
If no delimiter is provided then when mysql encounters any ; inside the store procedure or trigger it will think that as one statement and will try to execute it. So we need to provide a delimiter for store procedure or trigger and make mysql understand that anything within that delimiter is one complete set of code.
So in your example
SELECT * FROM products;
it will be a part of the complete statement when there is a delimiter other than ; is provided at the beginning.
I found two very strange problems in MySQL database.
My MySQL database version is 5.6.
Problem 1:
I have simple store procedure for update column value:
Store procedure is as below:
drop PROCEDURE if exists mysql_TestProc;
CREATE PROCEDURE mysql_TestProc(Finaltable VARCHAR(1024),ColTOProcess VARCHAR(1024)
,strFind TEXT,strReplace TEXT)
Label1:BEGIN
DECLARE code VARCHAR(1024) DEFAULT '00000' ;
-- Exception Handler
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
code = RETURNED_SQLSTATE;
END;
-- generate dynamic Query
SET #s:=CONCAT('UPDATE ',FinalTable,' SET
',ColTOProcess,'=REPLACE(',ColTOProcess,',\'',strFind,'\',\'',strReplace ,'\');');
PREPARE stmt from #s;
EXECUTE stmt;
-- If any exeption during query execution then Exception Handler will
-- assign error code to "code" variable
-- else "code" variable will have default value.
IF code != '00000' THEN
-- Error found..
select code ;
LEAVE Label1;
END IF;
END;
call mysql_TestProc("AnyTableName","ColumnName","Find Value","Replace Value").
If you call above store procedure with appropriate parameters it will
successfully update value.
But in my database It successfully update value with error code "42S22".
I changed machine then everything works fine.
So This strange behavior is only with my machine and my database("_temp").
Problem 2:
I have simple procedure as below:
DROP PROCEDURE IF EXISTS mysql_PrepareLogTable;
CREATE PROCEDURE mysql_PrepareLogTable(LogTable VARCHAR(1024),code TEXT,comment TEXT,category VARCHAR(1024),timestamp DATETIME,duration VARCHAR(100),rows INT,msg TEXT)
BEGIN
SET code=CONCAT(comment,' \n ',code);
SET #tempprepare=CONCAT('INSERT INTO ',LogTable,' VALUES ("',code,'","',category,'","',timestamp,'","',duration,'",',rows,',','"',msg,'")');
PREPARE stmt from #tempprepare;
EXECUTE stmt;
END;
I can compile above store procedure script all my mysql databases except one database("test2").
Only in database "test2", I am not able to compile above store procedure script.
Even I drop the store procedure and then try to execute the script but still It failed to compile script in database "test2".
I am using Toad 6 and mysql workbench 6.0.
So, anyone has any idea about these two problems.
Thank You,
Ronak
I'm interested in creating a trigger that will write a file after I import a csv into my table. The file name includes a time stamp and my code isn't working properly. Here's what I have so far.
DELIMITER $$
CREATE TRIGGER peachtree_trigger
AFTER INSERT ON peachtree
FOR EACH ROW
BEGIN
SET #sql_text = CONCAT("SELECT * FROM peachtree
INTO OUTFILE '/srv/samba/share/peachtree_",
DATE_FORMAT(NOW(), '%Y_%m_%D'), ".csv'");
PREPARE s1 FROM #sql_text;
EXECUTE s1;
DROP PREPARE s1;
END $$ DELIMITER ;
The set statement works fine outside of the trigger. However when I execute the above set of code and then try SHOW TRIGGERS IN test; it returns an empty set. If anyone could help I would be very grateful.
from http://dev.mysql.com/doc/refman/5.5/en/stored-program-restrictions.html
<snip>
SQL prepared statements (PREPARE, EXECUTE, DEALLOCATE PREPARE) can be used in stored procedures, but not stored functions or triggers. Thus, stored functions and triggers cannot use dynamic SQL (where you construct statements as strings and then execute them).
</snip>
My question may be stupid but I have a 2 days experience in MYSQL. I'm trying to use MyTAP for unit testing and face a problem .
here's the SQL code exucted on a mysql console:
drop procedure IF EXISTS tap.tstTableCount;
delimiter //
CREATE PROCEDURE tap.tstTableCount (IN db CHAR(64), IN tbl CHAR(64))
BEGIN
DECLARE l_sql VARCHAR (4000);
SET l_sql=CONCAT('SELECT COUNT(*)>0 FROM ',db,'.',tbl,';');
SET #sql=l_sql;
PREPARE s1 FROM #sql;
EXECUTE s1;
DEALLOCATE PREPARE s1;
END //
delimiter ;
call tap.tstTableCount('storibo','relationCategory'); /* This call works fine and returns 1 (true)*/
SELECT tap.ok(
tap.tstTableCount('storibo','relationCategory'),
'relationCategory contains data'
); /* this one returns :
ERROR 1305 (42000): FUNCTION tap.tstTableCount does not exist */
is it an issue with the MyTAP fmk or do I make a mistake in my syntax ?
The problem is your tap.tstTableCount is a PROCEDURE and not a FUNCTION. All the MyTAP tests are are FUNCTIONS, as noted by being able to call it in a SELECT statement. You cannot call a PROCEDURE from a SELECT statement, instead needing to call it via:
CALL tap.tstTableCount();
Unfortunately, your example is one that cannot simply be converted to a FUNCTION to be used by the mytap functions. Dynamic SQL is not permitted in FUNCTION, but is allowed in PROCEDURE.
Is it possible to create a trigger in MySQL using dynamically generated SQL from within a stored procedure? I am executing other dynamically constructed queries in my procedure by preparing a statement, but when I try the same approach to create a trigger I get the following error:
ERROR Code: 1295This command is not supported in the prepared statement protocol yet
From Bug #31625, PREPARED STATEMENT syntax does not allow to create TRIGGERS I see other people have been complaining about the same thing since 2007.
And from the look of WL#2871: Prepare any SQL it has not yet been fixed.
Is there a workaround for this problem? Is there another way of creating triggers with dynamic SQL?
Basically what I am trying to do is dynamically create triggers for recording audit data for inserts on various different tables. I am listing the tables I want to audit in an *audit_tables* table. The stripped-down procedure below iterates over the entries in that table and tries to create the trigger.
drop procedure if exists curtest;
delimiter |
create procedure curtest()
BEGIN
DECLARE done INT DEFAULT 0;
declare tn varchar(16);
declare cur cursor for select table_name from audit_tables;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
read_loop: LOOP
fetch cur into tn;
if done then
leave read_loop;
end if;
/* Create the BEFORE INSERT trigger */
set #sql = concat('CREATE TRIGGER audit_', tn, '_bi BEFORE INSERT ON ', tn, '
FOR EACH ROW BEGIN
set new.foo="bar";
END;');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
end LOOP;
close cur;
END;
|
delimiter ;
call curtest();
As the error you mention says, the CREATE TRIGGER command is not supported within prepared statements.
I think a more viable option is to use a scripting language that has MySQL bindings, like PHP, to automate the trigger creation. By the way, I just remembered that MySQL Workbench uses Lua as a scripting language for this sort of things.