一、实验目的
1.掌握触发器的概念,了解触发器的类型
2.掌握存储过程的创建与执行方法
二、实验内容
1、 创建触发器trigger_delete,实现以下功能:当订单表的数据被删除时,显示提示信息“订单表记录被修改了”。
CREATE TRIGGER trigger_delete
ON Sell_Order
AFTER DELETE
AS
PRINT '订单表记录被修改了';
2、 对Sell_Order表创建名为reminder的触发器,当用户向Sell_Order表中插入或修改记录时,自动显示Sell_Order表中的记录。
CREATE TRIGGER Trigger_reminder
ON Sell_Order
AFTER INSERT,UPDATE
AS
SELECT *
FROM Sell_Order
创建名为reminder的触发器时会命名冲突
3、 对Employee表中创建名为emp_updtri的触发器,实现如下功能:当修改姓名时,自动检查订单表,确定是否有该员工的订单,如果存在该员工,则撤销操作。
CREATE TRIGGER emp_upd
ON Employee
AFTER UPDATE
AS
IF UPDATE(EmployeeName)
DECLARE @ID INT
SELECT @ID=EmployeeID
FROM deleted
IF EXISTS(SELECT *
FROM Sell_Order
WHERE Sell_Order.SellOrderID=@ID)
BEGIN
PRINT '员工已存在订单'
ROLLBACK
END
4、 创建一个INSERT触发器,当在Employee表中插入一条新员工记录时,如果是“人事部”的员工,则撤销该插入操作,并返回出错消息。
ALTER TRIGGER Empoyee_Insert
ON Employee
AFTER INSERT
AS
DECLARE @DID CHAR(50)
SELECT @DID=DepartmentID FROM inserted
IF (SELECT DepartmentName
FROM Department
WHERE DepartmentID=@DID
)='人事部'
BEGIN
PRINT '禁止插入人事部成员'
ROLLBACK
END
5、 创建一个product_order_delete的触发器,其功能是:当删除商品表中的商品记录时,同时删除订单表中相应的订单,并显示提示信息“有关商品已被删除”。
CREATE TRIGGER product_order_delete
ON Product
INSTEAD OF DELETE
AS
DECLARE @Pid int
SELECT @Pid=ProductID
FROM deleted
DELETE
FROM Purchase_order
WHERE Purchase_order.ProductID=@Pid
DELETE
FROM Product
WHERE ProductID=@Pid
PRINT '有关商品已被删除'
6、 创建一个名为employee_deleted的触发器,其功能是:当对Employee表进行删除操作时,首先检查订单表,如果删除的员工没有接收订单,可以删除该员工的消息,否则撤销删除,显示“无法修改”的信息。
ALTER TRIGGER employee_delete
ON Employee
INSTEAD OF DELETE
AS
DECLARE @EID INT
SELECT @EID=EmployeeID
FROM deleted
IF EXISTS(SELECT SellOrderID
FROM Sell_Order
WHERE EmployeeID=@EID
)
BEGIN
PRINT '无法修改'
END
ELSE
DELETE
FROM Employee
WHERE EmployeeID=@EID