2

次のテーブルがあります。

RecordID
101
102
103
104
105
106

TableOne
101
102
103
104

TableTwo


TableThree
101
102

他のテーブルに含まれていない RecordsID 行を削除する必要があります。テーブル TableOne、TableTwo、TableThree の 1 つが空である場合があり、その場合はレコードを削除しないでください。

結果表は次のようになります。

RecordID
101
102

空のテーブルのため、INNER JOIN を使用できません。関数でこれらのコードを使用しているため、レコードを持つテーブルのみを含む動的 SQL ステートメントを作成して実行することはできません。

私は IF ステートメントでこれを行うことができましたが、私の実際の状況では、チェックするケースが多く、結合するテーブルが多く、結果として多くのコードの重複が発生しています。

そのため、CROSS APPLY を使用して、これをより賢く、よりクリーンにする方法はないかと考え始めました。

4

2 に答える 2

3

ここでクロス適用を使用する利点はありません。これが仕事をする簡単な解決策です:

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)

結果:

recordid
101
102
于 2012-10-23T10:56:44.960 に答える
0

例外とユニオンを使用する

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
于 2012-10-23T11:06:49.097 に答える