为了账号安全,请及时绑定邮箱和手机立即绑定

在SQL中我该怎么使用alter加入级联删除?怎么操作呢?

在SQL中我该怎么使用alter加入级联删除?怎么操作呢?

一只名叫tom的猫 2021-08-18 19:15:25
已经定义好的表create table SC(Sno char(9),Cno char(4),Grade smallint,PRIMARY KEY (Sno,Cno),FOREIGN KEY (Sno) REFERENCES Student(Sno),FOREIGN KEY (Cno) REFERENCES Course(Cno))现在想当删除Student中的某一项是同时把SC中的也删除。就是要达到create table SC(Sno char(9),Cno char(4),Grade smallint,PRIMARY KEY (Sno,Cno),FOREIGN KEY (Sno) REFERENCES Student(Sno)on delete cascade,FOREIGN KEY (Cno) REFERENCES Course(Cno))的效果,怎么用ALTER实现。
查看完整描述

2 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

这个简单哎
1.先删除已经建立的外键约束
alter table SC drop constraint 外键名 --外键名可在表架构里查到
2.重建外键约束并且加入级联删除项
Alter TABLE sc ADD CONSTRAINT [FK_sc] FOREIGN KEY (sno) REFERENCES student(sno)
ON Update CASCADE ON Delete CASCADE --本行表示级联删除的开启

查看完整回答
反对 回复 2021-08-23
?
撒科打诨

TA贡献1934条经验 获得超2个赞

建删除触发器 给你个例子
CREATE TRIGGER YHDZD_D ON YHDZD FOR DELETE AS
BEGIN
DECLARE @TMPCOUNT INT
SELECT @TMPCOUNT=@@ROWCOUNT

IF @@NESTLEVEL<>1
RETURN
IF Exists (select 1 from deleted where QZRQ<>null)
BEGIN
ROLLBACK TRANSACTION
ROLLBACK
TRIGGER WITH RAISERROR 17006 "已对帐的记录不能删除!"
RETURN
END

IF (@TMPCOUNT > 1) AND (@TMPCOUNT <> (select count(*) from deleted where QZRQ <>null))
BEGIN
ROLLBACK TRANSACTION
ROLLBACK TRIGGER WITH RAISERROR 17006
"有未对帐的记录存在!"
END
ELSE IF @TMPCOUNT > 1
BEGIN
RETURN
END

DECLARE @KMID Int
DECLARE @RQ smalldatetime
DECLARE @INX numeric(9,0)
DECLARE @DiffYE money
DECLARE curYHDZD_D CURSOR FOR
SELECT KMID,
RQ,INX,JFJE-DFJE FROM deleted
WHERE QZRQ=null

ORDER BY RQ,INX

OPEN curYHDZD_D
FETCH curYHDZD_D INTO @KMID,@RQ,@INX,@DiffYE
WHILE (@@sqlstatus = 0)
BEGIN
UPDATE YHDZD SET YE=YE-@DiffYE
WHERE KMID=@KMID AND (RQ>@RQ OR
RQ=@RQ AND INX>@INX)
FETCH curYHDZD_D INTO @KMID,@RQ,@INX,@DiffYE
END
CLOSE curYHDZD_D
DEALLOCATE CURSOR curYHDZD_D
END



查看完整回答
反对 回复 2021-08-23
  • 2 回答
  • 0 关注
  • 380 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信