数据库操作的问题!求高手指教学习!
假如我有三个表:A,B,C
A表里面有字段:ID,name
B表里面有字段:ID,Wage 字段ID是表A的外键。
表C里面有字段:ID ,name,Wage
当我要删除表A的一行数据时,必须要先删除表B里面对应ID的数据!但在删除之前要先把需要删除的个ID的A,B表中的数据插入到C表中,C表中的ID值等于A,B表被删除的ID值!!
例子:
A:1,牛
B:1,300
那么就应该是C:1,牛,300
然后A,B表ID=1的记录被删除!
百里面有人给我的答案:
create trigger trig_delete
on A表
for delete
as
begin
insert into c表
select A表.ID,A表.name,B表.Wage from A表 join B表
on A表.ID=B表.ID
where ID=(select ID from deleted);
delete B表
where ID=(select ID from deleted)
end
但是在执行过程中
select A表.ID,A表.name,B表.Wage from A表 join B表
on A表.ID=B表.ID
where ID=(select ID from deleted);
where中的ID不明确
改为: where A表.ID=(select ID from deleted);后可以创建了。
但是在删除A表中的ID=1的数据时还是提示与外键约束冲突!要先删除B表中的ID=1的
急啊,求高手解答!
------解决方案--------------------建个级联删除就行了
------解决方案--------------------我觉得可以用INSTEAD OF 代替 FOR
------解决方案--------------------SQL code
use CSDN
go
create table table_A(id int primary key, name nchar(10))
create table table_B(id int constraint FK_test foreign key(id) references table_A(id), wage int)
create table table_C(id int, name char(10), wage int)
insert into table_A
select 1, N'牛'
insert into table_B
select 1, 300
--=====================
create trigger trig_delete
on table_A
instead of delete
as
begin
insert into table_c
select
c.id,
a.name,
b.wage
from table_A a
inner join deleted c
on a.id = c.id
inner join table_B b
on a.id = b.id
delete B
from table_B B
inner join deleted A
on B.id = A.id
delete A
from table_A A
inner join deleted C
on A.id = C.id
end
go
--test
delete table_a