I have this code here:
CREATE TRIGGER testTrigger
AFTER INSERT ON users
BEGIN
DECLARE #uid VARCHAR(60)
SET #uid = (SELECT userid FROM inserted)
INSERT INTO user_locations (id,uid,lat,lng) VALUES (0,#uid,5.0,5.0)
END;
The idea is to insert generated user id into other table alongside some other data as soon as it hits the first 'users' table but phpMyAdmin gives this error code:
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
BEGIN
DECLARE #uid VARCHAR(60)
SET #uid = (SELECT userid FROM inserted)
at line 3
Can someone clarify why this trigger is bad?
I see four problems:
You have to use DELIMITERs so that your able to finish the commands with a semicolon as usual.
FOR EACH ROW is missing.
Use new.uid to access the recently inserted uid.
I'd also suggest using procedure variables instead of session-specific user-defined #variables, the latter ones being loosely typed and not declared as you've done.
But you don't even have to declare a variable. If you don't use phpMyAdmin:
DELIMITER //
CREATE TRIGGER testTrigger
AFTER INSERT ON users FOR EACH ROW
BEGIN
INSERT INTO user_locations (id,uid,lat,lng) VALUES (0,new.uid,5.0,5.0);
END//
DELIMITER ;
Check this answer about delimiter and the MySQL 5.7 docs on triggers and this answer about variables.
Edit, I overread you're using phpMyAdmin:
I don't use phpMyAdmin. But you can (stolen from here)
In phpMyAdmin, select the database that you want to work with.
Go to the SQL tab at the top of the page.
In the "Run SQL query/queries on database" form, change the Delimiter to $$. (Located in a small box at the bottom of the form)
Enter your SQL trigger into the main dialog box on the form. The correct syntax is as follows:
CREATE TRIGGER testTrigger
AFTER INSERT ON users FOR EACH ROW
BEGIN
INSERT INTO user_locations (id,uid,lat,lng) VALUES (0,new.uid,5.0,5.0);
END;$$
Hit "GO" with Super privilege.
Related
I am trying to create a stored procedure in MySQL that will add rows to two different tables. The first table (sites) has an id column set to auto_increment which I would like to include in the second insert statement to the sitesByUser table. I've tried some ideas based off this excellent post: https://dba.stackexchange.com/questions/2973/how-to-insert-values-into-a-table-from-a-select-query-in-postgresql but I get various errors, such as the one listed below. I suspect that part of my problem is that I'm trying to both add both userInput and SELECT id FROM sites WHERE id=LAST_INSERT_ID() to the same table, but I'm not sure what to do to get that to work.
CREATE PROCEDURE createSite(IN siteName VARCHAR(2048), IN userInput VARCHAR(255))
BEGIN
INSERT INTO sites(siteName, user) VALUES (siteName, userInput);
INSERT INTO sitesByUser(user, site) userInput, SELECT id FROM sites WHERE id=LAST_INSERT_ID();
SELECT * FROM sitesByUser WHERE id=LAST_INSERT_ID();
END
The response from MySQL:
Error while performing Query.
ER_PARSE_ERROR
ER_PARSE_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 'userInput, SELECT id FROM sites WHERE id=LAST_INSERT_ID();
SELECT * FROM sitesBy' at line 3
Try this
SET #last_id_in_table1 = LAST_INSERT_ID();
SELECT * FROM sitesByUser WHERE id=#last_id_in_table1;
Hope this helps
It seems that the correct way to do this is to store the LAST_INSERT_ID() in a variable as described here: How to declare a variable in MySQL? I'm not sure that I should be using the # symbol in front of the variable since that seems to make it a user-defined variable which means it is session-specific which is probably too wide in scope for my needs, but so far, this successfully creates a stored procedure that I think will work. I'll update this post if it does not.
CREATE PROCEDURE createSite(IN siteName VARCHAR(2048), IN userInput VARCHAR(255))
BEGIN
INSERT INTO sites(siteName, user) VALUES (siteName, userInput);
SET #last_id_in_sites = LAST_INSERT_ID();
INSERT INTO sitesByUser(user, site) VALUES (userInput, #last_id_in_sites);
SELECT * FROM sitesByUser WHERE id=LAST_INSERT_ID();
END
I am trying to create in MySQL a 'custom' unique ID based on existing primary key (auto-incremented) 'id' field
delimiter //
CREATE TRIGGER update_id AFTER INSERT ON test
BEGIN
UPDATE test SET PN="PN-"+NEW.id;
END;
//
delimiter ;
I am using PhpMyAdmin and I really don't know if it's a UI problem (I encountered some problems in the past while creating triggers in PhpMyAdmin) or I really do something wrong.
What I need is a custom PN field that is automatically updated when insert new records in table, based on some text prefix "PN-"
id PN other fields
-------------------------
...
...
...
1253 PN-1253
1254 PN-1254
#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 'BEGIN
UPDATE test SET PN="PN-"+NEW.id;
END' at line 2
I read in some other StackOverflow post that this will be impossible (to update) on the same table AFTER insert.
There is a solution with this? Thanks.
Get the new value and add it before insert
delimiter //
CREATE TRIGGER update_id BEFORE INSERT ON test
BEGIN
SET #pn:= ( SELECT AUTO_INCREMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME='test'
AND TABLE_SCHEMA=DATABASE() );
SET new.PN= CONCAT('PN-',#pn);
END;
//
delimiter ;
Here
Trying to create a transaction in phpmyadmin using the routine panel. I want to do an insert and an update:
START TRANSACTION;
INSERT INTO inventoryitems (item, quantity, userid)
VALUES(item, quantity, userid);
UPDATE users
SET cash = cash - (quantity * unitbuyprice);
COMMIT;
You can see the create/edit routine panel in the screen shot below:
Below is the error I get:
The following query has failed: "CREATE DEFINER=root#localhost PROCEDURE InsertInventoryItem(IN item VARCHAR(255), IN quantity INT, IN userid INT, IN unitbuyprice INT) NOT DETERMINISTIC NO SQL SQL SECURITY DEFINER START TRANSACTION; INSERT INTO inventoryitems (item, quantity, userid) VALUES(item, quantity, userid); UPDATE users SET cash = cash - (quantity * unitbuyprice); COMMIT;"
MySQL said: #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 'INSERT INTO inventoryitems (item, quantity, userid) VALUES(item, quantity, user' at line 3
If I remove the Start Transaction, Commit and either the insert or update then the procedure is fine. IE just a single statement works fine but multiple statements always gives an error.
What am I missing when I want to include multiple statements in a procedure.
I have tried with and without the semi colon delimiter.
This stuff just works with MS SQL. I have created Procedures with hundreds of statements inside before.
Cheers for the Help in advance.
I suggest you add BEGIN and END.
Also note:
A local variable should not have the same name as a table column. If an SQL statement ... contains a reference to a column and a declared local variable with the same name, MySQL currently interprets the reference as the name of a variable.
Reference: https://dev.mysql.com/doc/refman/5.7/en/local-variable-scope.html
If we implement control of transaction within the context of a stored program, we should probably also handle an error condition, and issue the rollback within the stored program. (Personally, I adhere to the school of thought that believes we should handle transaction context outside of the stored procedure.)
The procedure definition would look something like this:
DELIMITER $$
CREATE DEFINER=root#localhost PROCEDURE InsertInventoryItem(
IN as_item VARCHAR(255),
IN ai_quantity INT,
IN ai_userid INT,
IN ai_unitbuyprice INT
)
BEGIN
-- handle error conditions by issuing a ROLLBACK and exiting
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
EXIT PROCEDURE;
END;
START TRANSACTION ;
INSERT INTO inventoryitems (item, quantity, userid)
VALUES (as_item, ai_quantity, ai_userid) ;
UPDATE users u
SET u.cash = u.cash - (ai_quantity * ai_unitbuyprice)
WHERE u.userid = ai_userid ;
COMMIT ;
END$$
DELIMITER ;
--
Note that the update will assign a NULL to cash if either ai_quantity or ai_unitbuyprice is NULL. And we probably want a WHERE clause to limit the rows that will be updated. (Without the WHERE clause, the UPDATE statement will update all rows in the table.)
That's what the statements would look like if I wanted to create the procedure from a normal client, such as the mysql command line, or SQLyog.
MySQL syntax is significantly different than Transact-SQL (Microsoft SQL Server). We just have to deal with that.
As far as "this stuff just works with MS SQL", in all fairness, we should be careful to not conflate MySQL itself with the trouble prone idiot-syncracies of the phpMyAdmin client.
I'm trying to comprehend triggers, and I think I fully understand them, but I haven't been able to implement any of them. I want this code to delete a user with the name "test". So if anyone updates their name to "test" the user should be deleted.
My example code:
CREATE TRIGGER `my_trigger`
BEFORE UPDATE ON `my_db` FOR EACH ROW
BEGIN
DELETE FROM my_table WHERE `username` = 'test';
END
My 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 '' at line 4
I can't figure out why the delete statement is giving me an error. Any ideas?
Here is the syntaxically correct SQL:
DELIMITER ;
DROP TRIGGER IF EXISTS `my_trigger`;
DELIMITER $$
CREATE TRIGGER `my_trigger`
BEFORE UPDATE ON `my_table` FOR EACH ROW
BEGIN
DELETE FROM my_table WHERE `username` = 'test';
END$$
DELIMITER;
But it won't work, because you can't delete from the table, you are updating:
A trigger can access both old and new data in its own table. A trigger
can also affect other tables, but it is not permitted to modify a
table that is already being used (for reading or writing) by the
statement that invoked the function or trigger.
http://dev.mysql.com/doc/refman/5.5/en/faqs-triggers.html#qandaitem-B-5-1-9
If you want a simple example, try this:
DELIMITER ;
DROP TRIGGER IF EXISTS `my_trigger`;
DELIMITER $$
CREATE TRIGGER `my_trigger`
BEFORE UPDATE ON `my_table` FOR EACH ROW
BEGIN
SET NEW.`username` = 'aaa';
END$$
DELIMITER;
This will always set 'aaa' as the user name when updating.
It's possible to associated trigger only with a table.
Also within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.
Restrictions on Stored Programs
I am trying to set up a trigger on a table to copy the contents of a row into another table.
I have the following:
CREATE TRIGGER story_deleted BEFORE DELETE ON stories
FOR EACH ROW BEGIN
INSERT INTO stories_backup SET story_id = OLD.story_id;
END;
This returns the following error though:
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 can't work out where I'm going wrong with this. Any ideas?
Try changing the delimiter
DELIMITER $$
CREATE TRIGGER story_deleted BEFORE DELETE ON stories
FOR EACH ROW
BEGIN
INSERT INTO stories_backup SET story_id = OLD.story_id;
END $$
DELIMITER ;
and as far as your privileges go, run this query
SHOW GRANTS;
If SUPER is not there, you could
request your DBA to add that privilege for you
have your DBA create the trigger for you