问题描述:
我想做一个并唯简易的单板块的论坛,有帖子表和回复表,回复表里有帖子编号字段和回复编号字段,帖子编号是外键。有一个功能就是管理员把一条留言删除后相应的回复自动删除。请问在sql中如何设置
解析:
也可以用建立关系来实现,打开SQL中的“关系图”->建立关系图,然轿脊后选择你要建立关系的表,如果你的主键和外键已经建立好,则会自由关联,如果没有就手工拖一下,接下来就是选择“级联更新相关字段”和“级联删除相关字段”即可。
触发器方式: create trigger trg_A on A for update,delete as begin if exists(select 1 from inserted) update B set Name=(select Name from inserted) where Name=(select Name from deleted) else delete B where Name=(select Name from deleted) end go 要使用级联性更新和删除,用户可以在Alter TABLE 语句的CONSTRAINT子句中使用ON Update CASCADE 和/或 ON Delete CASCADE 关键字。注意他们都必须是应用于外键的。 级联更空没扮新和级斗灶联删除方式察逗: Alter TABLE [dbo].[T_USERGROUP] ADD CONSTRAINT [FK_T_USERGROUP_T_ACCTTEMPLATE] FOREIGN KEY ( [ATNAME] ) REFERENCES [dbo].[T_ACCTTEMPLATE] ( [ATNAME] ) ON Update CASCADE ON Delete CASCADE复制代码代码如下:
on
delete
cascade
当你更新或删除主键表时,轮裂那么卖握外键表也会跟随一起更新或删除,需要在建表时设置级联属性
CREATE
TABLE
Countries(CountryId
INT
PRIMARY
KEY)
INSERT
INTO
Countries
(CountryId)
VALUES
(1)
INSERT
INTO
Countries
(CountryId)
VALUES
(2)
INSERT
INTO
Countries
(CountryId)
VALUES
(3)
CREATE
TABLE
Cities(
CityId
INT
PRIMARY
KEY
,CountryId
INT
REFERENCES
Countries
ON
DELETE
CASCADE)
INSERT
INTO
Cities
VALUES(1,1)
INSERT
INTO
Cities
VALUES(2,1)
INSERT
INTO
Cities
VALUES(3,2)
CREATE
TABLE
Buyers(CustomerId
INT
PRIMARY
KEY
,CityId
INT
REFERENCES
Cities
ON
DELETE
CASCADE)
INSERT
INTO
Buyers
VALUES(1,1),
INSERT
INTO
Buyers
VALUES(2,1)
INSERT
INTO
Buyers
VALUES(3,2)
此外还中桐庆有级联更新
on
update
cascade
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)