SQL SERVER 用触发器实现在借阅或归还时自动修改图书的库存量
时间: 2024-02-17 08:03:04 浏览: 65
好的,您可以使用以下SQL Server触发器来实现在借阅或归还时自动修改图书的库存量:
```
CREATE TRIGGER update_book_inventory
ON book_transactions
AFTER INSERT, UPDATE
AS
BEGIN
DECLARE @book_id int,
@transaction_type varchar(10)
SELECT @book_id = book_id, @transaction_type = transaction_type
FROM inserted
IF @transaction_type = 'borrow'
BEGIN
UPDATE books
SET inventory = inventory - 1
WHERE book_id = @book_id
END
ELSE IF @transaction_type = 'return'
BEGIN
UPDATE books
SET inventory = inventory + 1
WHERE book_id = @book_id
END
END
```
该触发器将在`book_transactions`表中的插入或更新操作之后执行。当`transaction_type`为'borrow'时,将从`books`表中减去库存量,当`transaction_type`为'return'时,则将库存量加1。
阅读全文