为什么修改失败

来源:百度知道 编辑:UC知道 时间:2024/06/07 05:46:25
create database studb
go
use studb
create table s
(
stuid int primary key,
sname varchar(20)
)
create table c
(
cid int primary key identity(1,1),
stuid int references s(stuid),
score int
)
insert into s values(1,'aaa')
insert into c values (1,100)
create trigger te
on s
for update
as
declare @old int,@new int
select @old=stuid from deleted
select @new=stuid from inserted
if update(stuid)
begin
update c set stuid=@new where stuid=@old
end
go
update s set stuid=2 where stuid=1
我要修改s表中的stuid的同时要把c表中的stuid一起修改
注意c 表中的stuid是引用s 表中的主键,修改的答案我要运行的,通过了我才加分。有把握的才写啊。
不要给我说修改表结构哈,我要的是修改主键的同时把外键一起改掉。

declare @Check varchar(50),@sql nvarchar(2000)
select @Check=name from sysobjects where xtype='f' and parent_obj=object_id('c')
set @sql='alter table c drop constraint '+@Check --暂时去掉约束,记录外键约束名称
exec sp_executesql @sql
--此处执行updte
set @sql='alter table c add constraint '+@Check +'foreign key (stuid) REFERENCES s(stuid)'
exec sp_executesql @sql--恢复外键约束