我的存储过程的基本结构是,
BEGIN
.. Declare statements ..
START TRANSACTION;
.. Query 1 ..
.. Query 2 ..
.. Query 3 ..
COMMIT;
END
Run Code Online (Sandbox Code Playgroud)
MySQL版本: 5.1.61-0ubuntu0.11.10.1-log
目前,如果'query 2'失败,则提交'query 1'的结果.
如果SQL语句中有任何错误,系统将自动回滚更改,如何启动事务?
用PHP
try {
// First of all, let's begin a transaction
$db->beginTransaction();
// A set of queries; if one fails, an exception should be thrown
$db->query('first query');
$db->query('second query');
$db->query('third query');
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
$db->commit();
} catch (Exception $e) {
// An exception has been thrown
// We must rollback the transaction
$db->rollback();
} …Run Code Online (Sandbox Code Playgroud) 我需要更新bigtable包含另一个表(FK 约束到oldsmalltable)的id 的表 ( )的特定列,以指向另一个表上的 ID(FK 约束到newsmalltable)。基本上这就是我在做什么:
DELIMITER //
CREATE PROCEDURE updatebigtable ()
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION, SQLWARNING ROLLBACK;
START TRANSACTION;
ALTER TABLE bigtable DROP FOREIGN KEY bigtable_ibfk_1,
MODIFY smalltable_id SMALLINT ;
UPDATE bigtable SET smalltable_id=CASE smalltable_id
WHEN 1 THEN 1592
WHEN 2 THEN 1593
WHEN 3 THEN 1602
...
ELSE 0
END;
ALTER TABLE bigtable ADD CONSTRAINT bigtable_ibfk_1
FOREIGN KEY(smalltable_id) REFERENCES newsmalltable(id);
COMMIT;
END//
DELIMITER ;
CALL updatebigtable();
DROP PROCEDURE updatebigtable; …Run Code Online (Sandbox Code Playgroud) 我有一个 SQL 脚本,需要将其转换为参数化存储过程。我过去只编写过简单的函数,从未编写过带参数的复杂事务查询。
非常感谢任何帮助 - 下面简化了查询。该脚本实际上可以是包含交易和一些用户输入的任何内容。
-- transaction ensures i can clean up a mess, if one happens
begin;
-- parameters for the script; currently set manually before execution
set @parent_id := 123;
set @identifier := 'someid';
-- insert some row with user-specified values
insert into users (field1, field2) values (@parent_id, @identifier);
-- get the new id
set @user_id := last_insert_id();
-- do another insert
insert into usersmeta (user_id, field1, field2) values (@user_id, 1, 2);
-- if no errors happened …Run Code Online (Sandbox Code Playgroud)