存储过程和事务

create database ceshi
go
use ceshi
create table Users
(
   Id int primary key identity,
   Uname varchar(20)
)
insert  Users values('张三'),('李四')
select * from Users
--要求该表中只能添加5条数据,如果超过五条则执行回滚
语法:
begin transaction/tran(简写事务)
执行的sql语句以及一些判断
commit tran    --提交事务成功之后
rollback tran   --失败之后回滚

begin tran
 insert  Users values('何公冉')
 insert  Users values('何自宇')
 --保存保存数据的节点
 save tran aa
 insert  Users values('郭冲')
 insert  Users values('兴旺')
 --定义变量,获取表中一共有多少条数据
 declare @count int
 --给变量赋值    可以使用select或者是set
 set @count=(select count(1) from Users)
 --判断
 if @count>5
  begin  --代替c#中的{
   print '添加数量超过表中要求的总数量5条'
   rollback tran   aa  --执行回滚
  end   --代替c#中的}
 else
  begin
   print '添加成功'
   commit tran    --执行回滚
  end
 
--添加锁定时间
begin tran
update Users set Uname = '古巨基' where Id = 19
--设置锁定时间
waitfor delay '00:00:09'
commit tran

--建第二个事务
begin tran
select * from Users
commit tran
---------------------------------------------------------------------------------------------
alter proc Proc_SaleReturn
(
   @UId   int,
   @OId   int,
   @SaleCase    nvarchar(max),
   @SImg        nvarchar(max),
   @Count       int out
)
as
begin
  begin try
   begin tran
 
     insert into SaleInfoes values(@OId,@SaleCase,@SImg)
     set @Count=@@rowcount
     update OrdersInfoes set OState=3
     set @Count+=@@rowcount
     update GoodsInfoes set GNum+=(select ONum from OrdersInfoes where OId=@OId and UId=@UId) where GId=(select GId from OrdersInfoes where OId=@OId and UId=@UId)
     set @Count+=@@rowcount 
   commit tran
     end try 
 
     begin catch
        rollback tran
     set @Count=0
 end catch 
 return @Count
end
declare @C int
exec Proc_SaleReturn 1,3,'不想要','/Upload/3.png',@C out
select @C

select * from OrdersInfoes as o join GoodsInfoes as g on o.GId=g.GId
join UsersInfoes as u on o.UId=u.UId where u.UId=1
------------------------------------------------------------------------------------------------------
select * from OrderInfo as o join Shopping as s on o.ShopWid = s.ShopId where Oname = 'GuoQi'
go
alter proc My_proc
(
 @DelReson  nvarchar(100),
 @DelPicture  nvarchar(100),
 @OrderId  int,
 @Rults   int output
)
as
begin
 begin try
  begin tran
  insert into delOrderInfo values(@DelReson,@DelPicture,@OrderId)
  update Shopping set ShoNum+=1 where ShopId = (select ShopId from Shopping as s join OrderInfo as o on s.ShopId = o.ShopWid where o.Oid = @OrderId)
  commit tran
  set @Rults = 1
 end try
 begin catch
  rollback tran
 end catch
end
declare @rest int
exec My_proc 'asdas','asdas',1,@rest
select @rest
posted @ 2020-07-09 19:37  G蠢蠢  阅读(282)  评论(0编辑  收藏  举报