从SQL表中删除数据

时间:2012-01-18 11:58:07

标签: sql sql-delete

我有10个表,比如Table_1,Table_2,Table_3,Table_4 ...,Table_10 ..我必须删除除Table_4之外的所有表中的数据。是否有任何单行查询。(使用'LIKE','IN'等)“从表名中删除*,如Table_,其中表NOT IN('Table_4')”..

3 个答案:

答案 0 :(得分:1)

如果表的数量超过10,则不希望列出delete语句中的所有表。你应该坚持目录并使用游标:

declare @table nvarchar(max)
delcare @cur cursor

set @cur = cursor fast_forward for
  select name
  from sys.tables
  where name like 'Table_%'
  and name not like 'Table_4'

open @cur
fetch next from @cur into @table

while(@@fetch_status = 0)
begin
  sp_executesql 'DELETE FROM ' + @table

  fetch next from @cur into @table

end
close @cur
deallocate @cur

编辑:此答案仅适用于MS SQL:)

答案 1 :(得分:0)

use [db_name]

declare @sql nvarchar(max)

select @SQL = 
(select ';
DELETE FROM ' + quotename(TABLE_SCHEMA) + '.' + 
quotename(TABLE_NAME) from INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'
and TABLE_NAME not in ('mytab1', 'mytab2')

ORDER BY Table_Schema, TABLE_NAME
FOR XML PATH(''), type).value ('.','nvarchar(max)')

print @SQL -- verify

它将创建删除查询并使用此查询删除您需要的表并跳过您不需要。

答案 2 :(得分:-1)

使用Table_4

编写删除查询
delete from Table_1,Table_2,Table_3,Table_5,......Table10