create proc usp_CreateOrder
@OrderId nvarchar(50),
@UserId int,
@PostAddress nvarchar(255),
@TotalPrice money output
as
begin
declare @error int=0
begin transaction
--计算订单金额
select @TotalPrice = SUM([Count]*UnitPrice) from Cart inner join Books on Cart.BookId=Books.Id where Cart.UserId=@UserId
set @error = @error+@@ERROR
--生成订单
insert into Orders (OrderId,OrderDate,UserId,TotalPrice,PostAddress,[state]) values (@OrderId,GETDATE(),@UserId,@TotalPrice,@PostAddress,0)
set @error = @error+@@ERROR
--将购物车明细添加到订单明细
insert into OrderBook (OrderID,BookID,Quantity,UnitPrice) select @OrderId,BookId,[Count],UnitPrice from Cart inner join Books on Cart.BookId=Books.Id where Cart.UserId=@UserId
set @error = @error+@@ERROR
--删除购物车
delete from Cart where UserId=@UserId
set @error = @error+@@ERROR
--判断是否有错误
if(@error>0)
begin
rollback --如果有,回滚事务
end
else
begin
commit transaction --如果没有,提交事务
end
end
购物车数据生成订单-事务-存储过程
最新推荐文章于 2024-01-14 21:47:58 发布