use online_bookstore; CREATE TRIGGER trig1 on tb_bookinfo FOR UPDATE AS IF UPDATE(BookStoremount) BEGIN DECLARE @mount INT SET @mount = (SELECT BookStoremount FROM deleted) IF (@mount < 0) BEGIN PRINT '库存不足,库存为空' ROLLBACK END END以上代码有什么错误,该如何修改 以下代码如何断句create trigger trig2 on tb_orderdetail for insert,update as begin declare @mount int,@price money,@sigleprice money,@totalprice money set @mount=(select ordermount from inserted) set @totalprice=(select totalprice from tb_order,inserted where tb_order.orderid=inserted.orderid) set @price=(select bookprice from tb_bookinfo,inserted where tb_bookinfo.bookid=inserted.bookid) set @sigleprice=@mount*@price update tb_orderdetail set sigletotalprice=@sigleprice where orderdetailid=(select orderdetailid from inserted ) update tb_order set totalprice=(@totalprice+@sigleprice) where orderid=(select orderid from inserted) end go
时间: 2024-02-15 21:05:48 浏览: 78
在第一个代码段中,应该在IF语句中加入对BookStoremount列的判断条件,以防止其他列的更新也触发该触发器。同时,在触发器中应该使用ROLLBACK TRANSACTION语句来回滚事务。
正确的代码如下:
```
USE online_bookstore;
GO
CREATE TRIGGER trig1 ON tb_bookinfo FOR UPDATE
AS
IF UPDATE(BookStoremount)
BEGIN
DECLARE @mount INT
SET @mount = (SELECT BookStoremount FROM inserted)
IF (@mount < 0)
BEGIN
PRINT '库存不足,库存为空'
ROLLBACK TRANSACTION
END
END
GO
```
在第二个代码段中,应该使用逗号分隔符将INSERT和UPDATE操作分开,以便正确指定触发器应该响应的操作。
同时,应该使用JOIN语句来连接tb_order和inserted表,以便正确计算totalprice值。
正确的代码如下:
```
USE online_bookstore;
GO
CREATE TRIGGER trig2 ON tb_orderdetail FOR INSERT, UPDATE
AS
BEGIN
DECLARE @mount INT, @price MONEY, @sigleprice MONEY, @totalprice MONEY
SET @mount = (SELECT ordermount FROM inserted)
SET @totalprice = (SELECT SUM(tb_orderdetail.sigletotalprice) FROM tb_orderdetail WHERE tb_orderdetail.orderid = (SELECT orderid FROM inserted))
SET @price = (SELECT bookprice FROM tb_bookinfo WHERE tb_bookinfo.bookid = (SELECT bookid FROM inserted))
SET @sigleprice = @mount * @price
UPDATE tb_orderdetail SET sigletotalprice = @sigleprice WHERE orderdetailid = (SELECT orderdetailid FROM inserted)
UPDATE tb_order SET totalprice = @totalprice + @sigleprice FROM tb_order INNER JOIN inserted ON tb_order.orderid = inserted.orderid
END
GO
```
阅读全文