开发者

SQL Server: Try to Delete

I have a bunch of data in a table that serves as the parent (primary key in foreign key relationship) to several other tables. I basically want to go through this table and try and delete records that do not have children. I have already deleted the children, so there are parents that are childless.

If a record can be deleted, delete it, otherwise move onto the next record and don't show me that cannot delete error.

This isn't any kind of production need, I was just mess开发者_开发百科ing around with some test code and deleted some children, now I want to delete their sad parents.

This can either be done in sql or C# linq stuff. I basically just want to clear out my irrelevant data.


You could always try a query like

DELETE FROM ... WHERE NOT EXISTS (...


You can user an outer join - lets say you have master and child joining on id

delete m
from master m
left outer join child c 
on m.id = c.id
where c.id is null

What this does is join up all the records of master with the child and where the child doesn't exist it puts nulls in. You just need to select the ones where the child is null

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜