delete触发器出错了
------------这是我的两个表
Create Table Student( --学生表
StudentID int primary key, --学号
StydenName varchar(20) not null, --姓名
)
Create Table BorrowRecord( --学生借书记录表
BorrowRecord int identity(1,1), --流水号
StudentID int , --学号
BorrowDate datetime, --借出时间
ReturnDAte Datetime, --归还时间
)
----------这是我的测试数据
insert into Student values(1,'张三')
insert into Student values(2,'李四')
insert into Student values(3,'汪涵')
insert into BorrowRecord values(1,'2012-12-12','2012-12-12')
insert into BorrowRecord values(2,'2012-12-12','2012-12-12')
-------------这是触发器
Create trigger trdStudent
On Student
for Delete
As
Delete BorrowRecord
From BorrowRecord br , Delted d
Where br.StudentID=d.StudentID
go
----这是我的操作
delete from Student where StudentID = 1
--错误信息
消息 208,级别 16,状态 1,过程 trdStudent,第 5 行
对象名 'Delted' 无效。
------解决方案--------------------改成deleted 就行了
------解决方案--------------------Create trigger trdStudent
On Student
for Delete
As
Delete BorrowRecord
From BorrowRecord br , deleted d
Where br.StudentID=d.StudentID
go
注意红色部分
------解决方案--------------------1.旧记录的系统表叫做:deleted
2.你的删除命令本身也存在问题:你不能假设总是至删除一条记录
3.修改如下:
SQL code
Delete FROM BorrowRecord
Where StudentId IN (SELECT StudentId FROM DELETED);