Click here to Skip to main content
15,886,830 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a local database in which tables get generated at runtime only. While exiting the application I need to dop every tables in the database. How can I do this?

P.S-I dont need to drop entire database. I need to drop every tables inside it(Also, as tables are created at runtime, i dont have a name to refer them while doing drop command)
Posted
Updated 30-Dec-14 19:15pm
v2

1 solution

Use This script Clean all Database

SQL
/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO


For Mdf File Delete

I'm not sure what the point is of 'clearing the schema' - surely a new database already has a 'clear' schema.. BUT, you can create a new database in code via the following T-SQL:


"SQL"
CREATE DATABASE NewDb (NAME=NewDbFile, FILENAME= '<filepath>')


If you need a file (an MDF) you can then detach the database too with sp_detach_db and you can then move it as required from the location specified above:

SQL
EXEC sp_detach_db NewDb


To clear the data you can use sp_msforeachtable with a truncation command - it is a non-logged operation, and does not check constraints, nor foreign keys - however, it cannot be rolled back!

SQL
EXEC sp_msforeachtable 'TRUNCATE TABLE ?'
 
Share this answer
 
v5
Comments
arunkx 31-Dec-14 2:00am    
I am using MDF file as database. This is not working as a stored procedure in MDF file. Can you alter this so that it works in MDF file ?
Tushar sangani 31-Dec-14 2:24am    
create sp and cal at application close time
arunkx 1-Jan-15 23:42pm    
Thank You Tusharsangani :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900