T-SQL Using Cross-Apply with Delete Statement

前提是你 提交于 2020-01-04 07:02:39

问题


I have the following tables:

RecordID
101
102
103
104
105
106

TableOne
101
102
103
104

TableTwo


TableThree
101
102

and I need to delete the RecordsID rows, that are not included in the other tables. Please, note that sometimes the one of the tables TableOne,TableTwo,TableThree could be empty and no records should be deleted then.

The result table should be:

RecordID
101
102

Because of the empty tables I am not able to use INNER JOIN. And because I am using these code in a function I am not able to make a dynamic SQL statement containing only tables with records and executed it.

I could this with IF statements, but in my real situation I have many cases to check and many tables to join and a lot of code duplication is going as a result.

That's why I started to wonder is there a way to do this cleverer and cleaner with CROSS APPLY?


回答1:


I don't see any advanage in using cross apply here. Here is a simple solution that does the job:

declare @t table(recordid int)
declare @tableone table(recordid int)
declare @tabletwo table(recordid int)
declare @tablethree table(recordid int)
insert @t values(101),(102),(103),(104),(105),(106)

insert @tableone values(101),(102),(103),(104)
insert @tablethree values(101),(102)

delete t
from @t t
where not exists (select 1 from @tableone where t.recordid = recordid)
and exists (select 1 from @tableone)
or not exists (select 1 from @tabletwo where t.recordid = recordid)
and exists (select 1 from @tabletwo)
or not exists (select 1 from @tablethree where t.recordid = recordid)
and exists (select 1 from @tablethree)

Result:

recordid
101
102



回答2:


Use Except and Union

declare @t table(recordid int) 
declare @tableone table(recordid int) 
declare @tabletwo table(recordid int) 
declare @tablethree table(recordid int) 
insert @t values(101),(102),(103),(104),(105),(106) 

insert @tableone values(101),(102),(103),(104) 
insert @tablethree values(101),(102)

delete  
from @t where recordid not in(
select * from @t 
except select * from 
(select * from  @tableone union
select * from  @tabletwo union
select * from  @tablethree)x)

select * from @t


recordid
105
106


来源:https://stackoverflow.com/questions/13027482/t-sql-using-cross-apply-with-delete-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!