I have 10 tables , say Table_1,Table_2,Table_3,Table_4 ...,Table_10.. I have to delete data from all the tables except Table_4. Is there any single line query to do it.(Using 'LIKE','IN' etc) "Delete * from tablename like Table_ where Table NOT IN ('Table_4')"..
If the number of tables exceeds 10, you don't want to list all tables in the delete statement. You should stick to the catalog and use a cursor:
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
Edit: this answer is for MS SQL only :)
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
It will create query for delete and use this query delete the table u required and skip u not required.
用Table_4编写删除查询
delete from Table_1,Table_2,Table_3,Table_5,......Table10
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.