Trying to create a transaction in phpmyadmin - mysql

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.

Related

select from temporary table after call in mysql procedure

I am trying to make a reusable mysql procedure that takes data from join tables and store that in a temporary table. I will then create different procedures to select/calculate data from the result.
Here is my SQL code so far:
DELIMITER //
CREATE PROCEDURE getModulesForCourseYear(IN cid VARCHAR(10), IN yr INT(1))
CALL getModulesInCourse(cid);
SELECT * FROM modules WHERE year = yr;//
DELIMITER ;
The getModulesInCourse procedure creates a temporary table called modules
After getModulesInCourse is called in the procedure getModulesForCourseYear, I would then like to filter this result. This is where it fails.
I guess this is happening because mysql does not know what table modules is as it does not currently exist.
How would I be able to select from a temporary table in this procedure?
I am doing it in PHPMyAdmin which gives this error:
SQL query:
CREATE PROCEDURE getModulesForCourseYear(IN cid VARCHAR(10), IN yr INT(1))
CALL getModulesInCourse(cid);
SELECT * FROM modules WHERE year = yr;
MySQL said:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM modules WHERE year = yr' at line 3
NOTE: I am doing the procedure this way as I want to select the same initial data in multiple procedures, then I will filter it down. This way, it prevents duplicate code and if I need to change it later on, I can do so once.

How to create stored procedure that inserts both input and data from select statement after first insert

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

MySQL Insert after trigger clarification

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.

MySQL Stored Procedure works as plain SQL

I'm trying to write a stored procedure that inserts into one table (A), then queries another table (B), then finally inserts into table (C) the last insert id, along with the result from table B. I have written a stored procedure named VetIdFromCode to do the selecting from table B, which works fine in isolation. When I run the query in isolation, subbing in value for the IN parameters then it runs fine, but when I try and save it as a stored procedure it tells me invalid SQL near 'SET #LIID...'
Many thanks for any help.
CREATE PROCEDURE `NewClientUser`(
IN `uemail` VARCHAR(60),
IN `uphash` CHAR(40),
IN `uvcode` VARCHAR(11))
DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY INVOKER
INSERT INTO users (user_id,user_email,user_hash,user_role)
VALUES (NULL,uemail,uphash,'1');
SET #LIID = LAST_INSERT_ID();
CALL `VetIdFromCode`(uvcode, #VID);
INSERT INTO user_vet_lookup(user_id,vet_id)
VALUES (#LIID,#VID);
You need to start the "code" of the procedure with the key word "BEGIN" and put an "END" at the end. Like:
CREATE PROCEDURE `NewClientUser`(
IN `uemail` VARCHAR(60),
IN `uphash` CHAR(40),
IN `uvcode` VARCHAR(11))
BEGIN
DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY INVOKER
INSERT INTO users (user_id,user_email,user_hash,user_role)
VALUES (NULL,uemail,uphash,'1');
SET #LIID = LAST_INSERT_ID();
CALL `VetIdFromCode`(uvcode, #VID);
INSERT INTO user_vet_lookup(user_id,vet_id)
VALUES (#LIID,#VID);
END
Check out the documentation: http://dev.mysql.com/doc/refman/5.7/en/create-procedure.html

mysql and trigger usage question

I have a situation in which I don't want inserts to take place (the transaction should rollback) if a certain condition is met. I could write this logic in the application code, but say for some reason, it has to be written in MySQL itself (say clients written in different languages will be inserting into this MySQL InnoDB table) [that's a separate discussion].
Table definition:
CREATE TABLE table1(x int NOT NULL);
The trigger looks something like this:
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
NEW.x = NULL;
END IF;
END;
I am guessing it could also be written as(untested):
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
ROLLBACK;
END IF;
END;
But, this doesn't work:
CREATE TRIGGER t1 BEFORE INSERT ON table1 ROLLBACK;
You are guaranteed that:
Your DB will always be MySQL
Table type will always be InnoDB
That NOT NULL column will always stay the way it is
Question: Do you see anything objectionable in the 1st method?
From the trigger documentation:
The trigger cannot use statements that explicitly or implicitly begin or end a transaction such as START TRANSACTION, COMMIT, or ROLLBACK.
Your second option couldn't be created. However:
Failure of a trigger causes the statement to fail, so trigger failure also causes rollback.
So Eric's suggestion to use a query that is guaranteed to result in an error is the next option. However, MySQL doesn't have the ability to raise custom errors -- you'll have false positives to deal with. Encapsulating inside a stored procedure won't be any better, due to the lack of custom error handling...
If we knew more detail about what your condition is, it's possible it could be dealt with via a constraint.
Update
I've confirmed that though MySQL has CHECK constraint syntax, it's not enforced by any engine. If you lock down access to a table, you could handle limitation logic in a stored procedure. The following trigger won't work, because it is referencing the table being inserted to:
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
DECLARE num INT;
SET num = (SELECT COUNT(t.col)
FROM your_table t
WHERE t.col = NEW.col);
IF (num > 100) THEN
SET NEW.col = 1/0;
END IF;
END;
..results in MySQL error 1235.
Have you tried raising an error to force a rollback? For example:
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
SELECT 1/0 FROM table1 LIMIT 1
END IF;
END;