sql中怎样删除有外键的字段

Crazy_1015 2012-11-06 09:18:30
有两个表第一个userinfo 第二个MyNote 第二个表中有个外键是关联userID的 (userid为1)
现在我要删除userinfo表里的一个用户ID为1,直接删除的话会报错
请问怎样删除可以把用户删除了然后MyNote外键为1的也删除了,详细点。。。。。。谢谢
...全文
393 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
mstar1992 2014-12-30
  • 打赏
  • 举报
回复
Crazy_1015 2012-11-07
  • 打赏
  • 举报
回复
非常感谢 问题已解决 谢谢啊!
  • 打赏
  • 举报
回复
create table ta(
id int primary key,
name varchar(10)
)
go 
insert ta
select 1,'test' union all
select 2,'test'
go
create table tb
(
id int foreign key references ta(id),
name varchar(10)
)
insert tb
select 1,'test01' union all
select 2,'test01'
go
select * from tb
--直接删除:
delete from ta where id=1
/*
消息 547,级别 16,状态 0,第 1 行
DELETE 语句与 REFERENCE 约束"FK__tb__id__64CCF2AE"冲突。
该冲突发生于数据库"master",表"dbo.tb", column 'id'。
语句已终止。
*/
--处理方法
alter table tb
drop constraint  FK__tb__id__64CCF2AE
alter table tb
add  constraint  FK__tb__id__64CCF2AE foreign key(id) references ta(id)
on delete cascade

delete from ta where id=1

select * from ta
select * from tb

/*
id          name
----------- ----------
2           test

(1 行受影响)

id          name
----------- ----------
2           test01

(1 行受影响)


*/
Crazy_1015 2012-11-07
  • 打赏
  • 举报
回复
不行啊 在数据库里执行还是报错! 报的错是: (消息 1769,级别 16,状态 1,第 1 行 外键 'FK_MyNote_UserInfo' 引用了位于引用表 'MyNote' 中的无效列 'UserId'。 消息 1750,级别 16,状态 0,第 1 行 无法创建约束。请参阅前面的错误消息。) 我是这样写的: ( alter table MyNote add constraint FK_MyNote_UserInfo foreign key(CreateUser) references UserInfo(UserId) on delete cascade
ygnmn 2012-11-06
  • 打赏
  • 举报
回复
alter table mynote add constraint 外键名(aaa) foreign key(userid) references userinfo(userid) on delete cascade
ygnmn 2012-11-06
  • 打赏
  • 举报
回复
alter table 表名 add constraint 外键名 foreign key(字段名) references 主表名(字段名) on delete cascade

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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