Mariadb 存储过程是否总是需要启动事务?

Is start transaction always needed with Mariadb storedprocedure?

我有一个 mariadb 数据库和一个存储过程。如果 select 语句为真,则完成删除查询。像这样:


  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;

我的问题是,我是否需要将开始事务放在 select 语句之前的开头,或者以下是否可能?

  # 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;

第二个代码不需要回滚,仅在完成更改命令时才开始事务。

为什么要使用 IF?只需将其写为:

DELETE FROM category
    WHERE id = IN_category_uuid AND
          NOT EXISTS (SELECT 1 FROM products p WHERE p.categoryId = IN_category_uuid);

您可能不需要将其包装在事务中,但这可能取决于数据库的设置。通常,单个命令将在其自己的事务中(实际上没有太多要回滚的)。