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?
I don't see any advanage in using cross apply here. Here is a simple solution that does the job:
Result:
Use Except and Union