在Mysql儲存過程中使用事務例項

2021-07-10 05:55:42 字數 1438 閱讀 3772

create definer=`root`@`localhost` procedure `createbusiness`(parameter1 int)

begin

#routine body goes here...

declare flag int default parameter1;#宣告變數flag,將引數值賦給該變數

declare uuidstr varchar(32);#宣告乙個長度為32位的字串

declare currenttime timestamp;#宣告乙個型別為時間戳的變數

declare err int default 0;#宣告乙個整形變數err,預設值是0

declare continue handler for sqlexception set err=1;#當sqlexception handler捕捉到異常時,設定err=1

start transaction;#開始事務

while flag>0 do #注意: while不能空實現(在while塊中,裡面必須有語句)

#uuid()函式得到的字串是'6ccd780c-baba-1026-9564-0040f4311e29',剔除裡面的-,得到乙個32位的字串

set uuidstr = replace(uuid(),'-','') ;

#得到當前的時間

set currenttime = current_timestamp();

#執行插入語句,注意連線字串的函式concat(str1,str2,...);其中str..也可以是數字型別

insert into 

表名稱(id,title,keyword,hasimage,istodayhead,isshowinhome,isbigness,publishtime,originid,modify_time,isanalysis)

value

(uuidstr,concat('事件標題',flag),concat('關鍵字',flag),1,1,0,0,currenttime,concat('******x',flag),currenttime,1);

#每迴圈一次,flag要減去1,注意沒有flag--的語法

set flag = flag-1;

#在這裡測試當err=1時,事務是否有了回滾,測試ok

#if flag=7 then   #注意在procedure中給變數賦值要用到set,或在變數宣告時用default來父子,所以=號可以用來比較兩邊的值是否相等,<=>也可,區別先不去糾結。

#set err=1;

#end if;

end while;

if (err=0) then

commit;

select 'ok';

else

rollback;

select 'err';

end if;

end;

mysql儲存過程中使用事務

mysql儲存過程中使用事務 1 drop procedure ifexists test sp1 2create procedure test sp1 3begin 4declare t error integer default 0 5declare continue handler for s...

儲存過程中使用事務

create procedure updatewanjun username nvarchar 500 userpassword nvarchar 500 returnval int output as set xact abort on begin transaction t update adm...

在SQL Server儲存過程中使用事務及返回值

1 create procedure testtran23 as45declare userid int6 7set nocount on8 9begin tran adduser 1011 insert into testtable username,password,email values m...