sqlserver中--6. 创建一个名为tri_Delete_C的触发器,要求首先判断数据库中是否已经存在名为tri_Delete_C的触发器,如果存在,首先删除, --再创建,触发器要求删除一门课程时候,首先判断该课程有否有人选,如果有人选,则不能删除,并通过测试数据验证该触发器的执行情况;
时间: 2024-02-16 19:03:45 浏览: 67
以下是实现您所需的SQL Server触发器及测试示例:
1. 判断是否存在名为tri_Delete_C的触发器,如果存在则删除
```sql
IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'tri_Delete_C')
BEGIN
DROP TRIGGER tri_Delete_C;
END
GO
```
2. 创建触发器tri_Delete_C
```sql
CREATE TRIGGER tri_Delete_C
ON Course
INSTEAD OF DELETE
AS
BEGIN
-- 如果删除的课程有人选,则不允许删除
IF EXISTS (SELECT * FROM deleted d JOIN SC s ON d.cno = s.cno)
BEGIN
RAISERROR('该课程有人选,不能删除!', 16, 1);
END
ELSE
BEGIN
DELETE FROM Course WHERE cno IN (SELECT cno FROM deleted);
PRINT '删除成功!';
END
END;
GO
```
3. 测试触发器
```sql
-- 插入测试数据
INSERT INTO Course(cno, cname, ccredit)
VALUES('001', '数据库', 3.0),
('002', '操作系统', 4.0),
('003', '数据结构', 3.5);
INSERT INTO SC(sno, cno, grade)
VALUES('001', '001', 80),
('002', '002', 85),
('003', '001', 90);
-- 删除课程cno为001,因为有人选,所以会触发触发器
DELETE FROM Course WHERE cno = '001';
-- 删除课程cno为003,因为没有人选,所以可以成功删除
DELETE FROM Course WHERE cno = '003';
```
触发器执行结果:
```
Msg 50000, Level 16, State 1, Procedure tri_Delete_C, Line 9
该课程有人选,不能删除!
(1 row affected)
删除成功!
```
阅读全文