During Update Perform For Each On Last Insert ID - mysql

I have a very simple procedure which performs an update on multiple rows. Is their a way I can loop through the insert id of each updated row?
BEGIN
UPDATE testTable set testValue = 2
where username = inputUser and flag = 1;
//for each update performed, insert LAST_INSERT_ID() into tableB
END
is this possible? If so, can you lead me in the right direction?

LAST_INSERT_ID only gives you one last id. You can do multiple inserts without a loop. You can use the output of SELECT query and insert to the desired table. You can do something like that:
BEGIN
UPDATE testTable set testValue = 2
where username = inputUser and flag = 1;
INSERT into tableB (column1, column2)
SELECT column1, column2 FROM testTable
WHERE username = inputUser and flag = 1;
END
For example:
User (username, password)
UserLoginLog (username, last_log_in_date)
INSERT INTO UserLogInLog (username, last_log_in_date)
SELECT username, NOW()
FROM User
WHERE username = "JohnDoe"

Related

Can I make MySQL trigger events more detailed?

I am a beginner with MySQL. I want to create a trigger with a more specific condition (specific statement) than just INSERT, UPDATE, DROP, etc. For example, I would like something like the following:
CREATE TRIGGER name AFTER UPDATE table1 SET column1 = 'P' WHERE column2 = 'Q' FOR EACH ROW UPDATE table2 SET column1 = 42 WHERE column2 = 66;
Where AFTER UPDATE table1 SET column1 = 'P' WHERE column2 = 'Q' would be the trigger event and UPDATE table2 SET column1 = 42 WHERE column2 = 66 would be the trigger action.
You can check the old and new values for an UPDATE via the old and new pseudo rows. Of course you can use them in your logic.
CREATE TRIGGER name
AFTER UPDATE
ON table1
FOR EACH ROW
BEGIN
IF new.column1 = 'P'
AND old.column2 = 'Q' THEN
UPDATE table2
SET column1 = 42
WHERE column2 = 66;
END IF;
END;

Parameterized nested query

I'm trying to parameterize the following insert with a nested select.
INSERT IGNORE INTO table1 (creation_timestamp, str1, str2)
(SELECT now(), "param1", str2 FROM table2 WHERE key = "param2");
I'd like something like
INSERT IGNORE INTO table1 (creation_timestamp, str1, str2)
(SELECT now(), ?, str2 FROM table2 WHERE key = ?)
VALUES ("param1", "param2");
Anyone know how I can accomplish something like this?
Not exactly the same, but very similar.
You can use prepared statements:
http://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
Example:
PREPARE soExample
FROM 'INSERT
INTO usr (id, username, profile_pic)
VALUES (NULL, ?, (SELECT name
FROM customers
WHERE id = ?
LIMIT 1))';
SET #uname = "someUserNameForTheExample";
SET #id = "1";
EXECUTE soExample USING #uname, #id;
Or you can user procedure or/and functions as well
FUNCTION
DROP FUNCTION IF EXISTS insertExample$$
CREATE FUNCTION insertExample(userNameVar VARCHAR(255), uID INT(11)) RETURNS BOOLEAN
BEGIN
INSERT
INTO usr (id, username, profile_pic)
VALUES (NULL, userNameVar, (SELECT name
FROM customers
WHERE id = uID
LIMIT 1));
IF ROW_COUNT() > 0 THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END$$
FUNCTION USE
SELECT insertExample("SomeUsername" 2);
Perhaps you should start by reading https://dev.mysql.com/doc/refman/5.7/en/create-procedure.html. As Mysql Functions enables parameterized input for pre-build queries.

How can i add multiple insert statements in IF ELSE condition of MySql

I have a Stored procedure to insert or update multiple tables based on a value.
Ex:
BEGIN
select count(data) INTO #Update_Flag from tableA WHERE data = 20;
IF #Update_Flag > 0 THEN
UPDATE tableA SET data = 10 WHERE data1 = 20;
ELSE
INSERT INTO tableA SET data = 10,data1 = 20;
SELECT LAST_INSERT_ID() INTO #last_id;
INSERT INTO tableB (data, data1, data2) VALUES('0','1','2');
SELECT LAST_INSERT_ID() INTO #last_id1;
END IF;
END$$
Can anyone tell me what is the problem with above code.
Here my insert to tableA is working fine, but the next insert statements are not getting executed. Please share some solution.
Please try this :
Your code looks okay.
May be you've created a function and calling it like a procedure.
DROP PROCEDURE IF EXISTS sp_in_storedproc;
CREATE PROCEDURE `sp_in_storedproc`()
BEGIN
select count(data) INTO #Update_Flag from tableA WHERE data = 20;
IF #Update_Flag > 0 THEN
UPDATE tableA SET data = 10 WHERE data1 = 20;
ELSE
INSERT INTO tableA SET data = 10,data1 = 20;
SELECT LAST_INSERT_ID() INTO #last_id;
INSERT INTO tableB (data, data1, data2) VALUES('0','1','2');
SELECT LAST_INSERT_ID() INTO #last_id1;
END IF;
END;
Call this procedure like :
Call sp_in_storedproc();

IF Exists Then Update MySQL

I am trying to update a row if its exists, if it does not exist then I want to perform an insert into the table. The picture.id & picture.picturepath are a unique key. I have looked at some examples but I am not sure What I am doing wrong.
I have come across on duplicate key update, not sure if this is relevant to what I am trying to achieve.
Error message: 1064- You have an error in your SQL syntax near 'UPDATE picture SET picture.picturecontent = ipicturecontent WHERE picture.id at line 5"
IF EXISTS( SELECT * FROM picture WHERE picture.id = ipictureid
AND picture.picturepath = ipicturepath) THEN
UPDATE picture
SET picture.picturecontent = ipicturecontent
WHERE picture.id = ipictureid
AND picture.picturepath = ipicturepath
ELSE
INSERT INTO picture (picture.id, picture.picturecontent,picture.picturepath) VALUES (ipictureid, ipicturecontent, ipicturepath)
https://stackoverflow.com/a/10095812/1287480 <- Credit where credit is due
INSERT INTO models (col1, col2, col3)
VALUES ('foo', 'bar', 'alpha')
ON DUPLICATE KEY UPDATE col3='alpha';
don't forget THEN, BEGIN and END
IF EXISTS( SELECT * FROM picture WHERE id = ipictureid
AND picturepath = ipicturepath)
THEN
BEGIN
UPDATE picture
SET picturecontent = ipicturecontent
WHERE id = ipictureid
AND picturepath = ipicturepath
END;
ELSE
BEGIN
INSERT INTO picture (id,
picturecontent,
picturepath)
VALUES (ipictureid, ipicturecontent, ipicturepath)
END;
END IF;

IF STATEMENT in DELETE TRIGGER - FAILURE

So I've tried a whole lot of diffrent things with If statements, and i simply can't seem to work out how to do this.
I wan't to make the trigger delete the row with the lowest ID, if it recurring.
And by recurring i mean the number and username are the same in two rows.
For example
ROW1: ID: 1 , Nr: 1 , UN: MVJ and
Row2: ID: 2 , Nr: 1 , UN: MVJ
Those are recurring, but if the 'Nr' or 'UN' were different, they wouldn't be.
So here is my try so far.
CREATE TRIGGER no_double_reservations
AFTER INSERT ON tilmeldte
FOR EACH ROW
WHERE
'SELECT COUNT(*) from tilmeldte WHERE (kursus_nr, username) IN ( SELECT kursus_nr, username FROM tilmeldte GROUP BY kursus_nr, username HAVING count(*) = 2 )' = '2'
DELETE from tilmeldte Where tilmeldingsid =
'Select min(`tilmeldingsid`) from tilmeldte WHERE (kursus_nr, username) IN ( SELECT min(kursus_nr), username FROM tilmeldte GROUP BY kursus_nr, username HAVING count(*) = 2 )'
END;
Found the right syntax, but found out the move was impossible in SQL.
You can't delete a row from the same the table you select which row to delete.
The right syntax was:
DELIMITER !!
CREATE TRIGGER no_double_reservations
AFTER INSERT ON tilmeldte
FOR EACH ROW BEGIN
IF(
SELECT COUNT(*) from tilmeldte WHERE (kursus_nr, username) IN ( SELECT kursus_nr, username FROM tilmeldte GROUP BY kursus_nr, username HAVING count(*) = 2 ) = 2)
THEN
DELETE from tilmeldte Where tilmeldingsid = (Select min(`tilmeldingsid`) from tilmeldte WHERE (kursus_nr, username) IN ( SELECT min(kursus_nr), username FROM tilmeldte GROUP BY kursus_nr, username HAVING count(*) = 2 ));
END IF;
END!!
DELIMITER ;
Your trigger has some syntax errors, but those are somewhat unimportant, because what you are trying to do is not possible:
A stored function or trigger cannot 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.6/en/stored-program-restrictions.html
Triggers in MySQL cannot modify other rows in the table that the trigger is defined against. That would open up the possibility for infinite trigger recursion, e.g. a trigger on row A modifies row B, which fires a trigger that modifies row A, which fires a trigger that modifies row B, which...