3

各deleteステートメントに対して同じ条件(where句)を持つ複数のテーブルからデータを削除したいと思います。

delete from tblA where id in (select x.id from tblX x where name like N'%test%')
delete from tblB where id in (select x.id from tblX x where name like N'%test%')
delete from tblC where id in (select x.id from tblX x where name like N'%test%')
delete from tblD where id in (select x.id from tblX x where name like N'%test%')

上記のselectステートメントからIDを格納するリストを宣言する方法はありますか?

私は試した:

declare @ids int
set @ids = select x.id from tblX x where name like N'%test%'

しかし、それは不平を言います

サブクエリは複数の値を返しました。サブクエリが=、!=、<、<=、>、> =の後に続く場合、またはサブクエリが式として使用される場合、これは許可されません。

アドバイス、ありがとう。

4

3 に答える 3

10

とにかくテーブルが必要になりますが、少なくとも毎回同じように実行することで、大量の処理を回避できます。

-- create a table variable
declare @ids table
(
  id int not null
)

-- insert the id into the table variable
insert into @ids
select id from table1 where column1 like '%something%'

-- delete
delete from tablen where id in (select * from @ids)

一時テーブルを使用することもできます。同じように見えますが、@ idsの代わりに#idsが必要になり、ジョブの完了後に一時テーブルを削除する必要があります。

一時テーブル(物理テーブル)またはテーブル変数(テーブルのようなメモリ)のどちらかを選択するには、実際にいくつかのテストを実行する必要がありますが、定義上、複雑なデータは一時テーブルでより適切に機能します。少数のIDを短期間保持する必要がある場合は、テーブル変数の方が優れていると確信しています。

SQL Serverの一時テーブルとテーブル変数の違いは何ですか?

于 2013-02-22T18:59:35.333 に答える
2

一時テーブルを宣言してから、削除するIDをそのテーブルに選択することができます。

CREATE TABLE #IDS_from_tblA (id int)
INSERT INTO #IDS_from_tblA(id)
    SELECT x.id FROM tblA WHERE x.id in (select x.id from tblX x where name like N'%test%')
delete from tblA where id in (select x.id from tblX x where name like N'%test%')

(Do whatever you want to do with the ids)

DROP TABLE #IDS_from_tblA 
于 2013-02-22T19:00:52.660 に答える
2

SQLServer2008以降

declare @IdList table (Id int primary key)

insert into @IDList (Id)
select x.id from tblX x where name like N'%test%'

delete from tblA where id in (select x.id from @IDList x)

数百を超えるレコードがある場合は、テーブル変数の代わりに一時テーブルを使用できます。

于 2013-02-22T19:01:16.023 に答える