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

SQL server 2008 怎样根据从表中的一些条件删除主表中的某些元组
主表:Goods:

从表:Purchase:

从表Purchase中有如下语句:
PRIMARY KEY (Gno),
FOREIGN KEY (Gno) REFERENCES Goods(Gno)
删除所有Purchase中Num少于20个的商品信息,不包括Purchase中没有的商品(就是删除商品号Gno为1,2,5的)

------解决方案--------------------
引用:
Quote: 引用:

--先删除明细
delete purchase where num<20

--再删除主表
delete goods where Gno not in(select Gno from purchase)


看错了,应该这样

我一开始也是这样想的,但是这样会把不在从表Purchase中的M03给删除的,题目要求不要删除Goods中不在Purchase中的元组


这样呢,试试:

declare @temp table(gno varchar(30))


--先删除明细,会把删除的字段值,放到@temp表变量中
delete purchase 
output deleted.gno into @temp  
where num<20



--再删除主表
delete goods where Gno in (select Gno from @temp)