I have a mariadb database and a stored procedure. If a select statement is true then a delete query is done. Like this:
x
START TRANSACTION;
# Test if category is in use by a product and IN_category_uuid is an input variable
IF ((SELECT COUNT(id) FROM products WHERE categoryId = IN_category_uuid) = 0) THEN
DELETE FROM category WHERE id = IN_category_uuid;
COMMIT;
SET OUT_result = 0;
ELSE
ROLLBACK;
SET OUT_result = 2;
END IF;
My question is, do I need to place the start transaction at the beginning before the select statement or is the following possible?
# Test if category is in use by a product
IF ((SELECT COUNT(id) FROM products WHERE categoryId = IN_category_uuid) = 0) THEN
START TRANSACTION;
DELETE FROM category WHERE id = IN_category_uuid;
COMMIT;
SET OUT_result = 0;
ELSE
SET OUT_result = 2;
END IF;
This second code doesn’t require a rollback and only does a start transaction when a alter command is done.
Advertisement
Answer
Why use an IF
? Just write this as:
DELETE FROM category
WHERE id = IN_category_uuid AND
NOT EXISTS (SELECT 1 FROM products p WHERE p.categoryId = IN_category_uuid);
You probably don’t need to wrap this in a transaction, but that might depend on the settings for the database. In general, a single command will be in its own transaction (and there is not much to rollback, actually).