Hi this is my first Question here so I'm just posting some of my code here if you need some more information on the problem please ask.
I'm trying to create a trigger is MYSQL via PHPMyadmin (yes I know not the best tool).
The idea is to be able to clean a string before the insert query executes. Simple enough.
My code:
CREATE TRIGGER `CLEAR` BEFORE INSERT ON `TABLE`
FOR EACH ROW BEGIN
SET NEW.LNAME = REPLACE(NEW.LNAME,'?','');
END;
However I keep getting this error message
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
I have no idea why. any ideas are welcome thanks before hand.
Also excuse my not so good ise of the english language, I'm not a native speaker.
You've got to change the DELIMITER before the CREATE statement and set it back afterwards:
DELIMITER |
CREATE TRIGGER `CLEAR` BEFORE INSERT ON `TABLE`
FOR EACH ROW BEGIN
SET NEW.LNAME = REPLACE(NEW.LNAME,'?','');
END |
DELIMITER ;
otherwise you could write your trigger so it needs no delimiter:
CREATE TRIGGER `CLEAR` BEFORE INSERT ON `TABLE`
FOR EACH ROW
SET NEW.LNAME = REPLACE(NEW.LNAME,'?','')
Because there's only one statement executed in the trigger body, you don't have to enclose it in a BEGIN... END block and have no need of the semicolon to enc the statement too.
Related
I am using MySQL and I am defining a stored procedure like this:
delimiter ;;
Create procedure sp_test()
select * from name_table;
end
When I try to execute that procedure I get this error:
#2014 - Commands out of sync; you can't run this command now
What does this mean and what am I doing wrong?
From the reference manual section B.3.2.12 Commands out of sync:
B.3.2.12 Commands out of sync
If you get Commands out of sync; you can't run this command now in your client code, you are calling client
functions in the wrong order.
This can happen, for example, if you are using mysql_use_result() and
try to execute a new query before you have called mysql_free_result().
It can also happen if you try to execute two queries that return data
without calling mysql_use_result() or mysql_store_result() in between.
This post from the MySQL forums has this to say:
I've solved that problem. I use MySQL-Fron instead MySQL Query
browser. And everything works fine.
Makes me think that it's not a server or database problem but a problem in the tool you're using.
In my case, I had the following structure in my stored procedure:
DELIMITER //
DROP PROCEDURE IF EXISTS processcolumns;
CREATE PROCEDURE processcolumns ()
BEGIN
(...)
END //
DELIMITER ;
CALL processcolumns ();
DROP PROCEDURE processcolumns;
The problem relies here: DROP PROCEDURE IF EXISTS processcolumns;
I removed the semi colon ; and replaced it with the delimiter // like this:
DROP PROCEDURE IF EXISTS processcolumns //
And it's now solved!
I was able to reproduce this error with MySQL and phpmyadmin:
#2014 - Commands out of sync; you can't run this command now
On this version of MySQL:
el#apollo:~$ mysql --version
mysql Ver 14.14 Distrib 5.5.34, for debian-linux-gnu (x86_64) using readline 6.2
With the following SQL run through the phpmyadmin query window:
use my_database;
DELIMITER $$
CREATE PROCEDURE foo()
BEGIN
select 'derp' as 'msg';
END $$
CALL foo()$$ <----Error happens here, with or without delimiters.
I couldn't get the error to happen through the MySQL terminal, so I think it's a bug with phpmyadmin.
It works fine on the terminal:
mysql> delimiter $$
mysql> use my_database$$ create procedure foo() begin select 'derp' as 'msg'; end $$ call foo() $$
Database changed
Query OK, 0 rows affected (0.00 sec)
+------+
| msg |
+------+
| derp |
+------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
I think the bug has something to do with changing the delimiters mid-query within phpmyadmin.
Workaround: Slow down there, cowboy, and run your SQL statements one at a time when using phpmyadmin. phpmyadmin is "single task bob", he can only do one job.
The possible reason is that mysql client in your code is not thread safe, i encountered the same error when I call mysqldb in python, I have one mysql interface, used in 2 threads, the error happens. In this situation, you need to create more mysql interfaces along with threads.
I fixed this issue on phpMyAdmin 4.8.6
Issue: https://github.com/phpmyadmin/phpmyadmin/issues/14614
Pull-Request: https://github.com/phpmyadmin/phpmyadmin/pull/15234
The patch: https://github.com/phpmyadmin/phpmyadmin/pull/15234/files#diff-de1b7e9dd5969db226563678c658ea67
The patch consists into and if mysqli_more_results
then a call to mysqli_next_result
delimiter ;;
Create procedure sp_test()
select * from name_table;
end ## no end here, must add ;; after end. should be
delimiter ;;
Create procedure sp_test()
select * from name_table;
end ;;
Suppose that when you created the stored procedure you stored it in database named mydatabase to CALL the procedure. Go to your localhost DB and:
CALL mydatabase.sp_test();
Where sp_test() is the name of your procedure.
You forgot to use the 'Begin' keyword, and during compilation MySQL is confused, this should work:
DELIMITER ;;
Create procedure sp_test()
BEGIN
select * from name_table;
END;;
DELIMITER ;
I also encountered this problem with a C API.
I found the solution with the last example above, which speaks of delimiters.
use my_database;
DELIMITER $$
CREATE PROCEDURE foo()
BEGIN
select 'derp' as 'msg';
END $$
CALL foo()$$
My code executes a stored procedure then tests the return.
I use correctly the mysql_free_result().
Since I have not added a select clause "into" in the procedure, this error occurred.
The last example above is in the same case.
I have deleted the select and since it's ok.
Alex
I just got the same error from phpMYadmin when calling a user function I'm working on.
mysql console says however:
ERROR 1054 (42S22): Unknown column 'latitude' in 'field list'
...which is absolutely correct, it was misspelled in the field list, so a statement was referencing an undefined variable.
I'd have to conclude that
#2014 - Commands out of sync; you can't run this command now
from phpMYadmin is a rather non-specific error, than in many cases, if not most, is just obscuring the real problem, and one should not spend too much time trying to make sense out of it.
You have this problem apparently because both statements are executing simultaneously . The only workaround I have found is to close the connection after the sp and execute the other statement on a new one. Read about it here.
This was happening to me because a function within an procedure gave a value back that wasn't allocated to a variable.
The solution was:
select function .... INTO #XX;
It seems there are multiple sources for this issue. None of the posted answers worked in my case, I found that in my case I had selects and updates on a table in my stored procedure, the same table had an update trigger which was being triggered and sending the procedure into an infinite loop. Once the bug was found the error went away.
I also reproduced the issue in the case where I had a select which was calling a function which modified the table. It makes sense that these types of recursive calls could create issues. The issues were solved by updating a tmp table and at the end updating the original table from the tmp table.
I have made database trigger in mysql and in laravel it is working fine, however when I moved to postgresql I am getting error:
SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "BEGIN"
(I am new using postgresql btw)
Here is the code I've made in migration:
DB::unprepared('CREATE TRIGGER histories_insert AFTER INSERT ON packets FOR EACH ROW
BEGIN
IF new.status = "pending" THEN
insert into `histories` (`packet_id`, `message`, `created_at`, `updated_at`) VALUES (new.id, "Barang berhasil di buat", now(), now());
END IF;
END');
I really got confused about it. Hope someone can help me :)
The syntax and structure in mysql and postgre is different, in Postgres we have to write the trigger function (procedure) first then we called it in the body of our trigger
so after
FORE EACH ROW
There should be an
when event __type_of_event__
and then we call our trigger function
execute procedure __procedure_name__
Take a look at the doc about trigger here
and trigger procedure here
Noted that when event is optional, and the name of your field inside procedure should be change into plain text, or wrap it with double quotes (if it mixed with capital letter)
Don't worry about the version of documentation, postgresql trigger is consistent across versions, hope this helps!
You need to make it into a procedure:
From the docs:
PostgreSQL only allows the execution of a user-defined function for the triggered action. The standard allows the execution of a number of other SQL commands, such as CREATE TABLE, as the triggered action. This limitation is not hard to work around by creating a user-defined function that executes the desired commands.
DB::unprepared('CREATE TRIGGER histories_insert
AFTER INSERT ON packets
FOR EACH ROW
EXECUTE PROCEDURE that_procudure_you_wrote_with_that_content(new)');
As mentioned by Erdi, The syntax, and structure in MySQL is different than postgres.here is how you can write your migration for postgres Database:
CREATE OR REPLACE FUNCTION histories_insert()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.status = 'pending' THEN
INSERT INTO histories (packet_id, message, created_at, updated_at)
VALUES (NEW.id, 'Barang berhasil di buat', NOW(), NOW());
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER histories_insert
AFTER INSERT ON packets
FOR EACH ROW
EXECUTE FUNCTION histories_insert();
(Edit: Apologies for the funky formatting. SO was not having my code formatted.)
I feel dumb, but i've been racking my brain for this for longer then I like to admit.
I need a trigger that, when any update to menu_button is made, it updates a field in soa_config to the datetime the update was made (parameterValue is a Varchar). I've tried doing it as simple as setting parameterValue='1', no dice either. Running the update by itself, and the trigger, sans everything, and both work. It's the combination of the two that makes it hard. I get the error
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END' at line 1".
delimiter |
CREATE TRIGGER imatrigger AFTER UPDATE on `menu_button`
FOR EACH ROW
BEGIN
UPDATE soa_config
SET parameter_value = 'CURRENT_TIMESTAMP'
WHERE parameter_name = last_menu_update_itme
END
|
delimiter ;
I've looked at:
Quick MySQL Trigger Update
Trouble in creating Trigger in MySQL
MYSQL trigger trouble
sql creating a trigger on update
and more googling.
You need a statement delimiter after the WHERE clause and before the END statement
i.e. you should have a semi-colon here: WHERE parameter_name = last_menu_update_itme; <----
Okay, so I'm currently using mysqli_real_escape_string to escape my SQL queries before sending them to MySQL via PHP. Yet, for some reason my queries aren't processing, and when I outputted the MySQL query and pasted it in to PHPMyAdmin, it gave the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE ind={A$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQg' at line 1
Now, the following is my query:
INSERT INTO `db`.table(`colheader`) VALUES ('{\"hey\":[\"Hello world\",\"7\\/9\\/2013\"]}') WHERE ind='$6$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQgSnLHIlkBOtDTzu9AuZIZTr6GS4Rzr.iW11041994'
Now, I know that the string assigned to 'ind' has some issues, but I tried putting a slash before every period and every dollar sign and it still doesn't work. I tried putting the whole thing in double quotes, even brackets. Nothing. Could anyone point out what I'm clearly missing? I've looked at the documentation and can't seem to find anything. Thank you in advance!!
WHERE serves to filter which records will be affected or retrieved by your query, and INSERT servers to append a whole new record to a table.
An INSERT can never affect existing records, therefore its nonsense to have a WHERE clause. INSERT does not support WHERE.
If you are trying to edit the value of a field on an existing record, use UPDATE instead.
Take a look at the MySQL Reference Manual for details about its usage.
if your trying to make an update to the specified index use
UPDATE `db`.table SET `colheader` = '{\"hey\":[\"Hello world\",\"7\\/9\\/2013\"]}' WHERE ind='$6$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQgSnLHIlkBOtDTzu9AuZIZTr6GS4Rzr.iW11041994'
I've just learned the MySQL triggers and how they work. I decided to apply it on my small website.
I have a Users table where new users accounts are created and I would like to keep a history of adding new accounts in a UsersHistory table.
The error is that when I execute the following query, it gives me an error:
Query:
CREATE TRIGGER User_After_Insert
AFTER INSERT ON UsersHistory FOR EACH ROW WHEN NOT NEW.Deleted
BEGIN
SET #changeType = 'DELETE';
INSERT INTO UsersHistory (UserID, changeType)
VALUES (NEW.ID, #changeType);
END;
CREATE TRIGGER User_After_Insert1
AFTER INSERT ON UsersHistory FOR EACH ROW WHEN NEW.Deleted
BEGIN
SET #changeType = 'NEW';
INSERT INTO UsersHistory (UserID, changeType)
VALUES (NEW.ID, #changeType);
END;
The error is:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHEN NOT NEW.Deleted
BEGIN Â
SET #changeType = 'DELE' at line 1
I looked for a solution but I couldn't find.
Thanks
Have you set a DELIMITER to something different than ";"? Also, I saw some stuff I didn't know to be supported in mysql (the WHEN statements before the BEGIN blocks), so heres my suggestion:
delimiter //
CREATE TRIGGER User_After_Insert AFTER INSERT ON UsersHistory FOR EACH ROW
INSERT INTO UsersHistory (UserID, changeType) VALUES (NEW.ID, 'NEW')//
CREATE TRIGGER User_After_Delete AFTER DELETE ON UsersHistory FOR EACH ROW
INSERT INTO UsersHistory (UserID, changeType) VALUES (OLD.ID, 'DELETE')//
delimiter ;
UPDATE
Due to your comment below, I think you need to read up on trigger a bit more mate. But here's the gist.
The above statements, create triggers in the actual database. In effect, you "install" the triggers in your database schema. Running the statements in any mysql client, will create the triggers if you have appropriate account rights.
Now, from this stage on, you dont explicitly call them from PHP or anything like that. They live in the database and are called automatically when you perform certain actions. In the above case, AFTER a record is deleted from UserHistory or AFTER a record is inserted into UserHistory.
So, when you run "INSERT INTO UserHistory VALUES ..." from your php script, the database will fire the trigger automatically.
Hope that makes sence.