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')"..
Asked
Active
Viewed 617 times
0
-
What database? I haven't thought it through yet, but you might be able to get the table names from the schema and then do... something with them. – cha0site Jan 18 '12 at 11:59
-
does my link helped you? – Fahim Parkar Jan 18 '12 at 16:36
3 Answers
1
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 :)

Matten
- 17,365
- 2
- 42
- 64
-
It's not your's "**fault**" but it seems that writing the tables names is better... Less writing, More Readability, Works with every DB. =) – gdoron Jan 18 '12 at 12:19
-
-
1So you would have a lot more problems then delete their data... **lol** – gdoron Jan 18 '12 at 12:29
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
It will create query for delete and use this query delete the table u required and skip u not required.

Taja_100
- 453
- 6
- 15
-1
write a delete query with out Table_4
delete from Table_1,Table_2,Table_3,Table_5,......Table10

Nighil
- 4,099
- 7
- 30
- 56
-
what if you have thousands of tables?? will you keep on writing it manually? – Fahim Parkar Jan 18 '12 at 16:25
-
-
-