Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top