更改一门课程的课程号时,自动修改相应的选课记录的课程号。
然后我是这样写的, 在Course表中同时保存新的和旧的那条记录,等SC表更新好后,再把Course表中那条旧的删了。
但是一直仍有问题,
消息 2627,级别 14,状态 1,过程 alterCourseId,第 41 行
违反了 PRIMARY KEY 约束“PK__SC__6601161B66603565”。不能在对象“dbo.SC”中插入重复键。重复键值为 (1, 11)。谢谢~
alter trigger alterCourseId
on Course
instead of update
as
begin
print 'BEGIN'
if(UPDATE(cno))
begin
select * from deleted
select * from inserted
declare @oldcno int,@newcno int
declare @delcursor cursor
set @delcursor = cursor for
select cno from deleted
open @delcursor
declare @insercursor cursor
set @insercursor = cursor for
select cno from inserted
open @insercursor
fetch next from @delcursor into @oldcno
fetch next from @insercursor into @newcno
print @newcno
print @oldcno
while(@@FETCH_STATUS=0)
begin
print @newcno
print @oldcno
insert into Course
select @newcno,C1.CName
from Course as C1
where C1.CNO = @oldcno
update SC
set CNO = @newcno
where CNO = @oldcno
delete from Course
where Course.CNO = @oldcno
fetch next from @delcursor into @oldcno
fetch next from @insercursor into @newcno
end
close @delcursor
deallocate @delcursor
close @insercursor
deallocate @insercursor
end
end
GO
------解决思路----------------------
修改作为表关联的字段是不太好的方案, 如果一定要改, 最好添加外键,并设定更新规则是"联级", 这样数据库会自动同步修改子表