SQL Server2012在BookSale数据库中完成以下操作:创建一个事务,实现当向销售表插入新数据行时,如果库存数大于或等于销售数量,则允许销售,否则则拒绝销售
时间: 2024-03-30 21:35:16 浏览: 17
可以使用以下代码在SQL Server2012中创建一个事务,实现向销售表插入新数据行时的限制条件:
```
BEGIN TRANSACTION
DECLARE @Inventory INT
DECLARE @SaleQuantity INT
SELECT @Inventory = Inventory FROM Products WHERE ProductID = @ProductID
SELECT @SaleQuantity = @Quantity
IF @Inventory >= @SaleQuantity
BEGIN
INSERT INTO Sales (ProductID, SaleDate, Quantity) VALUES (@ProductID, GETDATE(), @SaleQuantity)
UPDATE Products SET Inventory = @Inventory - @SaleQuantity WHERE ProductID = @ProductID
COMMIT TRANSACTION
PRINT 'Sale completed successfully'
END
ELSE
BEGIN
ROLLBACK TRANSACTION
PRINT 'Sale rejected due to insufficient inventory'
END
```
其中,@ProductID 和 @Quantity 是插入新数据行时的产品ID和销售数量。该代码会先查询库存数,然后判断是否允许销售,如果允许,则向销售表插入新数据行,并更新库存数;否则,回滚事务并拒绝销售。