日期:2014-05-17  浏览次数:20676 次

sql中怎样删除有外键的字段
有两个表第一个userinfo 第二个MyNote 第二个表中有个外键是关联userID的 (userid为1)
现在我要删除userinfo表里的一个用户ID为1,直接删除的话会报错   
请问怎样删除可以把用户删除了然后MyNote外键为1的也删除了,详细点。。。。。。谢谢

------最佳解决方案--------------------
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 行受影响)


*/

------其他解决方案--------------------
alter table 表名
add constraint 外键名
foreign key(字段名) references 主表名(字段名)
on delete cascade


------其他解决方案--------------------
alter table mynote
add constraint 外键名(aaa)
foreign key(userid) references userinfo(userid)
on delete cascade


------其他解决方案--------------------
不行啊   在数据库里执行还是报错!
 报的错是:  (消息 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


 
------其他解决方案--------------------
非常感谢  问题已解决  谢谢啊!