sqlserver级联删除

wccwccwcw 2012-05-24 11:07:19
sqlserver怎么实现级联删除啊 求指教 最好来个通俗易懂的例子

我是弄个论坛 在删主题时报错 不能带着回复一起删掉

拜托了
...全文
167 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
wccwccwcw 2012-06-03
  • 打赏
  • 举报
回复
好的,我试试
Aaron_Chan 2012-05-25
  • 打赏
  • 举报
回复
[Quote=引用楼主 的回复:]
sqlserver怎么实现级联删除啊 求指教 最好来个通俗易懂的例子

我是弄个论坛 在删主题时报错 不能带着回复一起删掉

拜托了
[/Quote]

楼主,如果你的数据表已经建立好了,并且,你不希望更改你的表的话,你可以用“替代触发器”。
给你个简单的例子:

create trigger tri_d
on borrow
instead of delete
declare @bookid int
select @bookid=bookid from deleted
delete from borrow where bookid=@bookid
delete from book where bookid=@bookid

当你执行:
delete from book where bookid=1时,就会删除掉borrow中bookid=1与book表中id=1的数据库

  • 打赏
  • 举报
回复

--->>>>TravyLee生成测试数据
if object_id('test')is not null
drop table test
go
create table test(
id int primary key,
value varchar(10)
)
go
insert test(id,value)
select 1,'test1' union all
select 2,'test2' union all
select 3,'test3' union all
select 4,'test4' union all
select 5,'test5'
go


if object_id('tbl')is not null
drop table tbl
go
create table tbl(
id int foreign key references test(id)
on delete cascade --指定级联删除
on update cascade, --指定级联更新
value varchar(5)
)
go
insert tbl
select 1,'true' union all
select 2,'false' union all
select 3,'false' union all
select 4,'true' union all
select 5,'false'
go

delete from test where value='test2'


select * from test

/*
test数据
-------------------------
id value
1 test1
3 test3
4 test4
5 test5
-------------------------
tbl数据
--------------------------
id value
1 true
3 false
4 true
5 false
*/
koumingjie 2012-05-25
  • 打赏
  • 举报
回复

--级联删除
create table ta(id int not null primary key)
insert ta
select 1

create table tb(id int foreign key references ta(id) on delete cascade)
insert tb
select 1

select * from ta
select * from tb
delete ta
select * from ta
select * from tb

drop table tb
drop table ta


人生无悔 2012-05-24
  • 打赏
  • 举报
回复
on delete cascade--级联删除
on update cascade--级联更新

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧