存储过程PA和PB都是模拟用户这样的流程:先查询表A判断isflag是否为true,如果为true,就允许用户更新库存(库存量减一),并且把isflag更新为false.
如果查询表A判断isflag是否为false,则什么都不做.想要模拟这样的情景:用户甲先执行PA,在PA还未更新时,用户乙执行了PB并查询得到isflag为true,但要求最后只有用户甲能成功更新,因为甲先执行的
为了模拟上述情景,pA中延时了2秒如何构建上述情景?
下面是我的构建的脚本,有误
create table A(isFlag bool);
insert into A values(false);
create table B(id int,name char(1),count int); -- 库存表
insert into B values(1,1);DELIMITER $$
create procedure PA()
begin select @flag:=isFlag from A ;
select SLEEP(2);
if @flag
then
update B set count=count-1,name='A' where id=1;
update A set isflag=true;
end if;
commit;
end;DELIMITER $$
create procedure PB()
begin select @flag:=isFlag from A ; if @flag
then
update B set count=count-1,name='A' where id=1;
update A set isflag=true;
end if;
commit;
end;call PA();
call PB();
如果查询表A判断isflag是否为false,则什么都不做.想要模拟这样的情景:用户甲先执行PA,在PA还未更新时,用户乙执行了PB并查询得到isflag为true,但要求最后只有用户甲能成功更新,因为甲先执行的
为了模拟上述情景,pA中延时了2秒如何构建上述情景?
下面是我的构建的脚本,有误
create table A(isFlag bool);
insert into A values(false);
create table B(id int,name char(1),count int); -- 库存表
insert into B values(1,1);DELIMITER $$
create procedure PA()
begin select @flag:=isFlag from A ;
select SLEEP(2);
if @flag
then
update B set count=count-1,name='A' where id=1;
update A set isflag=true;
end if;
commit;
end;DELIMITER $$
create procedure PB()
begin select @flag:=isFlag from A ; if @flag
then
update B set count=count-1,name='A' where id=1;
update A set isflag=true;
end if;
commit;
end;call PA();
call PB();
代码如下:DELIMITER $$
create procedure PA()
begin
start transaction;
select concat(DATE_FORMAT(now(),'%Y-%i-%d %T')) 'Start PA:';
select @flag:=isFlag from A for update;
select SLEEP(5);
if @flag
then
update B set count=count-1,name='A' where id=1;
update A set isflag=true where id=1;
end if;
select concat(DATE_FORMAT(now(),'%Y-%i-%d %T')) 'End PA:';
commit;
end;DELIMITER $$
create procedure PB()
begin
start transaction;
select concat(DATE_FORMAT(now(),'%Y-%i-%d %T')) 'Start PB:';
select @flag:=isFlag from A ; if @flag
then
update B set count=count-1,name='A' where id=1;
update A set isflag=true where id=1;
end if;
select concat(DATE_FORMAT(now(),'%Y-%i-%d %T')) 'End PB:';
commit;
end;一个连接执行PA,然后一个连接执行PB,发现pb是没等pa执行完成就开始执行了,但a,b两个表都没更新
麻烦大家帮我看看