larrybg :
I'm writing a Node JS app and need to execute UPDATE
and DELETE
queries in the same statement, but DELETE
should be executed in another table and only if the condition equals a certain state. I'm not sure about my syntex... Here is what I have so far:
UPDATE vm_log SET user_id_fk = (SELECT user_id FROM users WHERE username = ?), vm_state = ? WHERE vm_id = ?;
SET @vmState = ?;
IF @vmState = 'PERMANENT' THEN
DELETE FROM vm_ext_tracking WHERE vm_fk = ?;
END IF
Where ?
are supplied as paramaters. For example username = 'someUser'
, vm_state = 'ACTIVE'
or PERMANENT
, and vm_id some number: vm_id = 4303
. The UPDATE
part works fine separately, just need to add a layer of complexity with DELETE
. The error message I receive:
#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 'IF @vmState = 'PERMANENT' THEN
DELETE FROM vm_ext_tracking WHERE vm_fk = 4303' at line 1
Akina :
UPDATE vm_log
SET user_id_fk = ( SELECT user_id
FROM users
WHERE username = ?),
vm_state = ?
WHERE vm_id = ?;
SET @vmState = ?;
DELETE
FROM vm_ext_tracking
WHERE vm_fk = ?
AND @vmState = 'PERMANENT';
PS. @vmState
is excess, if you do not need in it in the below (not shown) code you may use
UPDATE vm_log
SET user_id_fk = ( SELECT user_id
FROM users
WHERE username = ?),
vm_state = ?
WHERE vm_id = ?;
DELETE
FROM vm_ext_tracking
WHERE ? = 'PERMANENT'
AND vm_fk = ?;