How to drop all tables from a database with one SQL query? - sql

I don't want to type all tables' name to drop all of them. Is it possible with one query?

Use the INFORMATION_SCHEMA.TABLES view to get the list of tables. Generate Drop scripts in the select statement and drop it using Dynamic SQL:
DECLARE #sql NVARCHAR(max)=''
SELECT #sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Exec Sp_executesql #sql
Sys.Tables Version
DECLARE #sql NVARCHAR(max)=''
SELECT #sql += ' Drop table ' + QUOTENAME(s.NAME) + '.' + QUOTENAME(t.NAME) + '; '
FROM sys.tables t
JOIN sys.schemas s
ON t.[schema_id] = s.[schema_id]
WHERE t.type = 'U'
Exec sp_executesql #sql
Note: If you have any foreign Keys defined between tables then first run the below query to disable all foreign keys present in your database.
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
For more information, check here.

If you want to use only one SQL query to delete all tables you can use this:
EXEC sp_MSforeachtable #command1 = "DROP TABLE ?"
This is a hidden Stored Procedure in sql server, and will be executed for each table in the database you're connected.
Note: You may need to execute the query a few times to delete all tables due to dependencies.
Note2: To avoid the first note, before running the query, first check if there foreign keys relations to any table. If there are then just disable foreign key constraint by running the query bellow:
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

If you don't want to type, you can create the statements with this:
USE Databasename
SELECT 'DROP TABLE [' + name + '];'
FROM sys.tables
Then copy and paste into a new SSMS window to run it.

The simplest way is to drop the whole database and create it once again:
drop database db_name
create database db_name
That's all.

You could also use the following script to drop everything, including the following:
non-system stored procedures
views
functions
foreign key constraints
primary key constraints
system_versioning
tables
https://michaelreichenbach.de/how-to-drop-everything-in-a-mssql-database/
/* Drop all non-system stored procs */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])
WHILE #name is not null
BEGIN
SELECT #SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Procedure: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
/* Drop all views */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP VIEW [dbo].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped View: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
/* Drop all functions */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP FUNCTION [dbo].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Function: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
/* Drop all Foreign Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE #name is not null
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
WHILE #constraint IS NOT NULL
BEGIN
SELECT #SQL = 'ALTER TABLE [dbo].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint) +']'
EXEC (#SQL)
PRINT 'Dropped FK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE #name IS NOT NULL
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
WHILE #constraint is not null
BEGIN
SELECT #SQL = 'ALTER TABLE [dbo].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint)+']'
EXEC (#SQL)
PRINT 'Dropped PK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* Remove system versioning */
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
IF OBJECTPROPERTY(OBJECT_ID(' + #name + '), 'TableTemporalType') = 2
SELECT #SQL = 'ALTER TABLE [dbo].[' + RTRIM(#name) +'] SET (SYSTEM_VERSIONING = OFF); ALTER TABLE [dbo].[' + RTRIM(#name) + '] DROP PERIOD FOR SYSTEM_TIME;'
EXEC (#SQL)
PRINT 'System Versioning Disabled for Table: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
/* 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

As a follow-up to Dave.Gugg's answer, this would be the code someone would need to get all the DROP TABLE lines in MySQL:
SELECT CONCAT('DROP TABLE ', TABLE_NAME, ';')
FROM INFORMATION_SCHEMA.tables
WHERE TABLE_SCHEMA = 'your_database_name'

I'd just make a small change to #NoDisplayName's answer and use QUOTENAME() on the TABLE_NAME column and also include the TABLE_SCHEMA column encase the tables aren't in the dbo schema.
DECLARE #sql nvarchar(max) = '';
SELECT #sql += 'DROP TABLE ' + QUOTENAME([TABLE_SCHEMA]) + '.' + QUOTENAME([TABLE_NAME]) + ';'
FROM [INFORMATION_SCHEMA].[TABLES]
WHERE [TABLE_TYPE] = 'BASE TABLE';
EXEC SP_EXECUTESQL #sql;
Or using sys schema views (as per #swasheck's comment):
DECLARE #sql nvarchar(max) = '';
SELECT #sql += 'DROP TABLE ' + QUOTENAME([S].[name]) + '.' + QUOTENAME([T].[name]) + ';'
FROM [sys].[tables] AS [T]
INNER JOIN [sys].[schemas] AS [S] ON ([T].[schema_id] = [S].[schema_id])
WHERE [T].[type] = 'U' AND [T].[is_ms_shipped] = 0;
EXEC SP_EXECUTESQL #sql;

If anybody else had a problem with best answer's solution (including disabling foreign keys), here is another solution from me:
-- CLEAN DB
USE [DB_NAME]
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
DECLARE #Sql NVARCHAR(500) DECLARE #Cursor CURSOR
SET #Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN #Cursor FETCH NEXT FROM #Cursor INTO #Sql
WHILE (##FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL #Sql
FETCH NEXT
FROM #Cursor INTO #Sql
END
CLOSE #Cursor DEALLOCATE #Cursor
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL'

Not quite 1 query, still quite short and sweet:
-- Disable all referential integrity constraints
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
-- Drop all PKs and FKs
declare #sql nvarchar(max)
SELECT #sql = STUFF((SELECT '; ' + 'ALTER TABLE ' + Table_Name +' drop constraint ' + Constraint_Name from Information_Schema.CONSTRAINT_TABLE_USAGE ORDER BY Constraint_Name FOR XML PATH('')),1,1,'')
EXECUTE (#sql)
GO
-- Drop all tables
EXEC sp_msforeachtable 'DROP TABLE ?'
GO

Use the following script to drop all constraints:
DECLARE #sql NVARCHAR(max)=''
SELECT #sql += ' ALTER TABLE ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + ' NOCHECK CONSTRAINT all; '
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Exec Sp_executesql #sql
Then run the following to drop all tables:
select #sql='';
SELECT #sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Exec Sp_executesql #sql
This worked for me in Azure SQL Database where 'sp_msforeachtable' was not available!

I Know this question is very old but every Time i need this code .. by the way if you have tables and views and Functions and PROCEDURES you can delete it all by this Script ..
so why i post this Script ?? because if u delete all tables you will need to delete all views and if you have Functions and PROCEDURES you need to delete it too
i Hope it will help someone
DECLARE #sql NVARCHAR(max)=''
SELECT #sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME)
+ '; '
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Exec Sp_executesql #sql
DECLARE #sql VARCHAR(MAX) = ''
, #crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;
SELECT #sql = #sql + 'DROP VIEW ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
QUOTENAME(v.name) +';' + #crlf
FROM sys.views v
PRINT #sql;
EXEC(#sql);
declare #procName varchar(500)
declare cur cursor
for select [name] from sys.objects where type = 'p'
open cur
fetch next from cur into #procName
while ##fetch_status = 0
begin
exec('drop procedure [' + #procName + ']')
fetch next from cur into #procName
end
close cur
deallocate cur
Declare #sql NVARCHAR(MAX) = N'';
SELECT #sql = #sql + N' DROP FUNCTION '
+ QUOTENAME(SCHEMA_NAME(schema_id))
+ N'.' + QUOTENAME(name)
FROM sys.objects
WHERE type_desc LIKE '%FUNCTION%';
Exec sp_executesql #sql
GO

Try this
DROP DATABASE database_name;
CREATE DATABASE database_name;
This will delete the database and create a new database with the same name

I‘d do it with a loop for all tables if you’re using like oracle or sqlite:
FOR i IN (SELECT ut.table_name
FROM USER_TABLES ut) LOOP
EXECUTE IMMEDIATE 'drop table '|| i.table_name ||' CASCADE CONSTRAINTS ';
END LOOP;

For me I just do
DECLARE #cnt INT = 0;
WHILE #cnt < 10 --Change this if all tables are not dropped with one run
BEGIN
SET #cnt = #cnt + 1;
EXEC sp_MSforeachtable #command1 = "DROP TABLE ?"
END

Related

How to delete everything from a database (tables, views, stored procedures, functions)?

I want to drop everything in the database, tables, views, stored procedures, and functions. I found some link but they don't work on complex database. It failed to drop tables. This is my own version of the script that I found on this website and tweak it.
/* Drop all non-system stored procs */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.procedures WHERE [name] = #name)
WHILE #name is not null
BEGIN
SELECT #SQL = 'DROP PROCEDURE [' + #schema + '].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Procedure: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > #name ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.procedures WHERE [name] = #name)
END
GO
/* Drop all views */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.views WHERE [name] = #name)
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP VIEW [' + #schema + '].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped View: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > #name ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.views WHERE [name] = #name)
END
GO
/* Drop all Foreign Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
SELECT #schema = (SELECT TOP 1 CONSTRAINT_SCHEMA FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE #name is not null
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = #name AND CONSTRAINT_SCHEMA = #schema ORDER BY CONSTRAINT_NAME)
WHILE #constraint IS NOT NULL
BEGIN
SELECT #SQL = 'ALTER TABLE [' + #schema + '].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint) +']'
--BEGIN TRY
EXEC (#SQL)
PRINT 'Dropped FK Constraint: ' + #constraint + ' on ' + #name
--END TRY
--BEGIN CATCH
-- PRINT (#SQL)
--END CATCH
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name AND CONSTRAINT_SCHEMA = #schema ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
SELECT #schema = (SELECT TOP 1 CONSTRAINT_SCHEMA FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
SELECT #schema = (SELECT TOP 1 CONSTRAINT_SCHEMA FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE #name IS NOT NULL
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = #name AND CONSTRAINT_SCHEMA = #schema ORDER BY CONSTRAINT_NAME)
WHILE #constraint is not null
BEGIN
SELECT #SQL = 'ALTER TABLE [' + #schema + '].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint)+']'
IF #SQL LIKE '%PK_arrival_detail%' BEGIN PRINT #SQL END
EXEC (#SQL)
PRINT 'Dropped PK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
SELECT #schema = (SELECT TOP 1 CONSTRAINT_SCHEMA FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all tables */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.tables WHERE [name] = #name)
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP TABLE [' + #schema + '].[' + 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])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.tables WHERE [name] = #name)
END
GO
/* Drop all functions */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.objects WHERE [name] = #name)
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP FUNCTION [' + #schema + '].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Function: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > #name ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.objects WHERE [name] = #name)
END
GO
The problem is only on the drop constraints and drop tables. It always failed with tables that have relationship to another table. How can I fix my script to make it works on more complex database?
The script you provided is almost completed. I have adjust a few where condition here and there to make it more robust in complex case. This version is support delete 2 objects that have same name but difference schema. I also added a section to drop database trigger because it might prevent you to delete tables in some cases.
I have tested this with AdventureWorks Databases and my own database (which somewhat very complex.)
/* Drop all non-system stored procs */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.procedures WHERE [name] = #name)
WHILE #name is not null
BEGIN
SELECT #SQL = 'DROP PROCEDURE [' + #schema + '].[' + RTRIM(#name) +']'
--PRINT (#SQL)
EXEC (#SQL)
PRINT 'Dropped Procedure: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.procedures WHERE [name] = #name)
END
GO
/* Drop all database triggers */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 T.name FROM sys.triggers AS T WHERE T.parent_id = 0 /* database trigger */ ORDER BY [name])
WHILE #name is not null
BEGIN
SELECT #SQL = 'DROP TRIGGER [' + RTRIM(#name) +'] ON DATABASE'
EXEC (#SQL)
PRINT 'Dropped TRIGGER: ' + #name
SELECT #name = (SELECT TOP 1 T.name FROM sys.triggers AS T WHERE T.parent_id = 0 /* database trigger */ AND [name] > #name ORDER BY [name])
END
GO
/* Drop all views */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.views WHERE [name] = #name)
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP VIEW [' + #schema + '].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped View: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > #name ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.views WHERE [name] = #name)
END
GO
/* Drop all Foreign Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
SELECT #schema = (SELECT TOP 1 CONSTRAINT_SCHEMA FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE #name is not null
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = #name AND CONSTRAINT_SCHEMA = #schema ORDER BY CONSTRAINT_NAME)
WHILE #constraint IS NOT NULL
BEGIN
SELECT #SQL = 'ALTER TABLE [' + #schema + '].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint) +']'
BEGIN TRY
EXEC (#SQL)
PRINT 'Dropped FK Constraint: ' + #constraint + ' on ' + #name
END TRY
BEGIN CATCH
PRINT (#SQL)
END CATCH
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name AND CONSTRAINT_SCHEMA = #schema ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
SELECT #schema = (SELECT TOP 1 CONSTRAINT_SCHEMA FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
SELECT #schema = (SELECT TOP 1 CONSTRAINT_SCHEMA FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE #name IS NOT NULL
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = #name AND CONSTRAINT_SCHEMA = #schema ORDER BY CONSTRAINT_NAME)
WHILE #constraint is not null
BEGIN
SELECT #SQL = 'ALTER TABLE [' + #schema + '].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint)+']'
--PRINT #SQL
EXEC (#SQL)
PRINT 'Dropped PK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name AND CONSTRAINT_SCHEMA = #schema ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
SELECT #schema = (SELECT TOP 1 CONSTRAINT_SCHEMA FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all tables */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.tables WHERE [name] = #name)
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP TABLE [' + #schema + '].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Table: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.tables WHERE [name] = #name)
END
GO
/* Drop all functions */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.objects WHERE [name] = #name)
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP FUNCTION [' + #schema + '].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Function: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > #name ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.objects WHERE [name] = #name)
END
GO
/* Drop all types */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
DECLARE #schema VARCHAR(128)
SELECT #name = (SELECT TOP 1 [name] FROM sys.types WHERE is_user_defined = 1 ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.types WHERE [name] = #name)
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP TYPE [' + #schema + '].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped type: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sys.types WHERE is_user_defined = 1 AND [name] > #name ORDER BY [name])
SELECT #schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.types WHERE [name] = #name)
END
GO
Please refer these links:
Drop All Objects in a SQL Server Database
List Schema Name and Table Name for Database
I would normally suggest the same approach as the other answer, but since that doesn't seem to be working for you, here's a whole different angle on it...
Generating the drop statements in the right order to get around the constraints is complex, but fortunately there's a whole niche market for schema modification tools to figure it out for you. Here's one approach that worked for me:
Create a blank database on a local SQL Server which uses the same version of SQL Server as the target
Download the trial version of Red Gate SQL Compare (other similar vendor products may work too)
SQL Compare the local blank DB against the target DB, and run the script it generates for you
Again, not saying Red Gate is the only tool for it. Other vendors claim similar features, it's just that Red Gate is the one I use. Note also they have an SDK if you're trying to embed this in some larger process or script.

How to drop all tables from a database in sql server 2005 in a statement except one table

I am using sql-server 2005. Initially, for learning purpose I created many tables now I want to drop all those tables except one which is currently I am working on.
Is there any code or query with which I can drop all tables from my that database except that one useful table.
One way I think is to copy that table into new database using SELECT INTO... clause and drop that database but don't know is this a good way to solve this problem.
If the tables aren't very big I'd probably just select them all in the "Object Explorer Details" window in SSMS then hit delete.
For a programmatic solution you could use
EXEC sys.sp_MSforeachtable
N'IF OBJECT_ID(''?'') <> OBJECT_ID(''dbo.YourTableToKeep'')
DROP TABLE ?
'
Both methods might need repeated runs in order to delete all tables involved in FK relationships (a table cannot be deleted if another table has an FK referencing it).
You can use sql to create all drops staments that you needs. For example the next sql query
USE [MyDatabase];
GO
SELECT
replace(
replace('DROP TABLE [{Schema}].[{TableName}];'
,'{Schema}',TABLE_SCHEMA)
,'{TableName}',TABLE_NAME)
FROM
INFORMATION_SCHEMA.TABLES
WHERE
TABLE_NAME NOT IN ('TableNameOne','TableNameTwo')
and get the result executing the query.
Copy first column of the query and paste it in a new query window.
It's easy to see, that you get a list of drop staments for all tables except 'TableNameOne' and 'TableNameTwo',...
Im think that is very simple...
/* Drop all Foreign Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE #name is not null
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
WHILE #constraint IS NOT NULL
BEGIN
SELECT #SQL = 'ALTER TABLE [dbo].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint) +']'
EXEC (#SQL)
PRINT 'Dropped FK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE #name IS NOT NULL
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
WHILE #constraint is not null
BEGIN
SELECT #SQL = 'ALTER TABLE [dbo].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint)+']'
EXEC (#SQL)
PRINT 'Dropped PK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* 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

Dropping a table with all its dependencies (Microsoft SQL Server)

How can I drop a table with all its dependencies [SPs, Views, etc.] (Microsoft SQL Server) without knowing its dependencies upfront? I know I can display all dependencies in Mangement Studio but I'm searching for utility script that I could simply speficy an object and it would drop this object with all its dependencies.
The best thing to do it is "Generate scripts for Drop"
Select Database -> Right Click -> Tasks -> Generate Scripts - will open wizard for generating scripts
Select the database -> next
Set option 'Script to create' to true (want to create)
Set option 'Script to Drop' to true (want to drop)
Set option 'Generate script for dependent object' to true -> Next
Select the Check box to select objects wish to create script
Select the choice to write script (File, New window, Clipboard)
Execute the script
This way we can customize our script i.e., we can do scripting for selected objects of a database.
I hope this will help you!
Best Wishes, JP
You can use Sp_Depends to find the dependencies. With that you can modify the script from this answer Maybe someone less lazy than me will do that for you.
Note: Each object of course could have its own dependencies so you'll need to process them as well.
Delete a SQL object using its schema-qualified name. For tables, the constraints are dropped first.
Errors are ignored.
create procedure [dbo].[spDropObject] (#fullname nvarchar(520))
as
begin
begin try
declare #type nvarchar(5)
declare #resolvedFullname nvarchar(520)
declare #resolvedName nvarchar(255)
set #type = null
set #resolvedFullname = null
set #resolvedName = null
--find the object
select
#type = o.[type]
,#resolvedFullname = '[' + object_schema_name(o.id) + '].[' + o.[name] + ']'
,#resolvedName = '[' + o.[name] + ']'
from dbo.sysobjects o
where id = object_id(#fullname)
--PROCEDURE
if(#type = 'P')
begin
exec('drop procedure ' + #resolvedFullname);
return;
end
--VIEW
if(#type = 'V')
begin
exec('drop view ' + #resolvedFullname);
return;
end
--FUNCTION
if(#type = 'FN' or #type = 'TF')
begin
exec('drop function ' + #resolvedFullname);
return;
end
--TRIGGER
if(#type = 'TF')
begin
exec('drop trigger ' + #resolvedFullname);
return;
end
--CONSTRAINT
if(#type = 'C' or #type = 'UQ' or #type = 'D' or #type = 'F' or #type = 'PK' or #type = 'K')
begin
declare #fullTablename nvarchar(520);
set #fullTablename = null
--find the contraint's table
select #fullTablename ='[' + object_schema_name(t.[object_id]) + '].[' + t.[Name] + ']'
from sys.tables t
join sys.schemas s on t.schema_id = s.schema_id
where t.object_id = (select parent_obj from dbo.sysobjects where id = object_id(#resolvedFullname))
exec('alter table ' + #fullTablename + ' drop constraint ' + #resolvedName);
return;
end
--TABLE (drop all constraints then drop the table)
if(#type = 'U')
begin
--find FK references to the table
declare #fktab table([Name] nvarchar(255))
insert #fktab
select
[Name] = '[' + object_name(fkc.[constraint_object_id]) + ']'
/*
,[Parent] = '[' + object_schema_name(fkc.[parent_object_id]) + '].[' + object_name(fkc.[parent_object_id]) + ']'
,[Ref] = '[' + object_schema_name(fkc.[referenced_object_id]) + '].[' + object_name(fkc.[referenced_object_id]) + ']'
*/
from sys.foreign_key_columns as fkc
where referenced_object_id = object_id(#resolvedFullname)
order by [Name]
--iterate FKs
while(1=1)
begin
declare #constraint nvarchar(255)
set #constraint = null
select top 1
#constraint = [Name]
from #fktab
if(#constraint is not null)
begin
--drop FK constraint
exec [dbo].[spDropObject] #constraint;
delete from #fktab where [Name] = #constraint --remove current record from working table
end
else break;
end
--find constraints for table
declare #constraintTab table ([Name] nvarchar(255));
insert #constraintTab
select [name]
from sys.objects
where parent_object_id = object_id(#resolvedFullname)
order by [name]
--iterate constraints
while(1=1)
begin
set #constraint = null;
select top 1 #constraint = [Name] from #constraintTab
if(#constraint is not null)
begin
--drop constraint
exec [dbo].[spDropObject] #constraint;
delete from #constraintTab where [Name] = #constraint --remove current record from working table
end
else break;
end
--drop table
exec('drop table ' + #resolvedFullname);
return;
end
end try
begin catch
declare #message nvarchar(max)
set #message = error_message( ) ;
print #message
end catch
end
In my case, I specifically wanted to drop a specified table and the tables that depend on that table. It wasn't useful to me to only drop the foreign key constraints that reference it. I wrote a stored procedure to do this
CREATE PROCEDURE DropDependentTables (
#tableName NVARCHAR(64))
AS
-- Find and drop all tables that depend on #tableName
WHILE EXISTS(SELECT *
FROM sys.foreign_keys
WHERE OBJECT_NAME(referenced_object_id) = #tableName AND
OBJECT_NAME(parent_object_id) != #tableName)
BEGIN
DECLARE #dependentTableName NVARCHAR(64)
SELECT TOP 1 #dependentTableName = OBJECT_NAME(parent_object_id)
FROM sys.foreign_keys
WHERE OBJECT_NAME(referenced_object_id) = #tableName AND
OBJECT_NAME(parent_object_id) != #tableName
EXEC DropDependentTables #dependentTableName
END
I'm going to leave a late answer (after around 10 years). I hope you'll find it handy.
In our company, we use this script to properly delete database tables. For each table, we first drop the dependencies (REFERENTIAL_CONSTRAINTS) then delete the table itself.
USE [database-name]
DECLARE #Sql NVARCHAR(500) DECLARE #Cursor CURSOR
SET #Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_SCHEMA + '].[' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + '];'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN #Cursor FETCH NEXT FROM #Cursor INTO #Sql
WHILE (##FETCH_STATUS = 0)
BEGIN
Exec sp_executesql #Sql
FETCH NEXT FROM #Cursor INTO #Sql
END
CLOSE #Cursor DEALLOCATE #Cursor
GO
EXEC sp_MSforeachtable 'DROP TABLE ?'
GO
The credit goes to a colleague of mine, Abolfazl Najafzade, for the script.

SQL Server: drop table cascade equivalent?

In oracle, to drop all tables and constraints you would type something like
DROP TABLE myTable CASCADE CONSTRAINTS PURGE;
and this would completely delete the tables and their dependencies. What's the SQL server equivalent??
In SQL Server Management Studio, go to Options / SQL Server Object Explorer / Scripting, and enable 'Generate script for dependent objects'. Then right click the table, script > drop to > new query window and it will generate it for you.
I don't believe SQL has a similarly elegant solution. You have to drop any related constraints first before you can drop the table.
Fortunately, this is all stored in the information schema and you can access that to get your whack list.
This blog post should be able to get you what you need:
http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx
-- t-sql scriptlet to drop all constraints on a table
DECLARE #database nvarchar(50)
DECLARE #table nvarchar(50)
set #database = 'DatabaseName'
set #table = 'TableName'
DECLARE #sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = #database and table_name = #table)
BEGIN
select #sql = 'ALTER TABLE ' + #table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = #database and
table_name = #table
exec sp_executesql #sql
END
This might be a horrible solution, but I find it's quick. It is similar to Vinnie's answer, but the product of the SQL statement is another series of SQL statements that will delete all constraints and tables.
(
select
'ALTER TABLE ' + tc.table_name + ' DROP CONSTRAINT ' + tc.constraint_name + ';'
from
INFORMATION_SCHEMA.TABLES t
,INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
where
t.table_name = tc.table_name
and tc.constraint_name not like '%_pk'
and tc.constraint_name not like 'pk_%'
and t.table_catalog='<schema>'
) UNION (
select
'DROP TABLE ' + t.table_name + ';'
from
INFORMATION_SCHEMA.TABLES t
where
t.table_catalog='<schema>'
)
This is all fun and games until some table references your table...
Then I must alter the code provided like so :
CREATE PROCEDURE _cascadeConstraints #database nvarchar(30) = NULL, #table nvarchar(60) = NULL
as
DECLARE #sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = #database and table_name = #table)
BEGIN
select #sql = 'ALTER TABLE ' + #table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = #database and
table_name = #table
select #sql = 'ALTER TABLE ' + tc.TABLE_NAME + ' DROP CONSTRAINT ' + tc.CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc join
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc on
(rc.CONSTRAINT_CATALOG = tc.CONSTRAINT_CATALOG and
rc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME) join
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc_pk on
(tc_pk.CONSTRAINT_CATALOG = rc.CONSTRAINT_CATALOG and
tc_pk.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME)
where tc.constraint_catalog = #database
and tc_pk.TABLE_NAME = #table
exec sp_executesql #sql
END
go
Ultimately we are deleting our table.
So we can simply run 2 following command:
ALTER TABLE ... DROP CONSTRAINT ...
DROP TABLE ...
1> ALTER TABLE PRJ_DETAILS DROP CONSTRAINT FK_PRJ_TYPE;
-- Table name and Constraint Name are the parameter
2> DROP TABLE .
First drop constraint with its name associated with it table
Second you can drop table.
It worked for me and its easy also.
I just need delete the foreign key
DECLARE #database nvarchar(50)
DECLARE #TABLE_NAME nvarchar(250)
DECLARE #CONSTRAINT_NAME nvarchar(250)
DECLARE #sql nvarchar(350)
set #database = 'XXX'
DECLARE db_cursor CURSOR FOR
select TABLE_NAME, CONSTRAINT_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = #database and CONSTRAINT_TYPE='FOREIGN KEY'
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #TABLE_NAME, #CONSTRAINT_NAME
WHILE ##FETCH_STATUS = 0
BEGIN
select #sql = 'ALTER TABLE ' + #TABLE_NAME + ' DROP CONSTRAINT ' + #CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = #database and
table_name = #TABLE_NAME
exec sp_executesql #sql
FETCH NEXT FROM db_cursor INTO #TABLE_NAME, #CONSTRAINT_NAME
END
CLOSE db_cursor
DEALLOCATE db_cursor

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

Is there any way in which I can clean a database in SQl Server 2005 by dropping all the tables and deleting stored procedures, triggers, constraints and all the dependencies in one SQL statement?
REASON FOR REQUEST:
I want to have a DB script for cleaning up an existing DB which is not in use rather than creating new ones, especially when you have to put in a request to your DB admin and wait for a while to get it done!
this script cleans all views, SPS, functions PKs, FKs and tables.
/* Drop all non-system stored procs */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])
WHILE #name is not null
BEGIN
SELECT #SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Procedure: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
/* Drop all views */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP VIEW [dbo].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped View: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
/* Drop all functions */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP FUNCTION [dbo].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Function: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
/* Drop all Foreign Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE #name is not null
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
WHILE #constraint IS NOT NULL
BEGIN
SELECT #SQL = 'ALTER TABLE [dbo].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint) +']'
EXEC (#SQL)
PRINT 'Dropped FK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE #name IS NOT NULL
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
WHILE #constraint is not null
BEGIN
SELECT #SQL = 'ALTER TABLE [dbo].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint)+']'
EXEC (#SQL)
PRINT 'Dropped PK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* 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
I'm using this script by Adam Anderson, updated to support objects in other schemas than dbo.
declare #n char(1)
set #n = char(10)
declare #stmt nvarchar(max)
-- procedures
select #stmt = isnull( #stmt + #n, '' ) +
'drop procedure [' + schema_name(schema_id) + '].[' + name + ']'
from sys.procedures
-- check constraints
select #stmt = isnull( #stmt + #n, '' ) +
'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.check_constraints
-- functions
select #stmt = isnull( #stmt + #n, '' ) +
'drop function [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects
where type in ( 'FN', 'IF', 'TF' )
-- views
select #stmt = isnull( #stmt + #n, '' ) +
'drop view [' + schema_name(schema_id) + '].[' + name + ']'
from sys.views
-- foreign keys
select #stmt = isnull( #stmt + #n, '' ) +
'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.foreign_keys
-- tables
select #stmt = isnull( #stmt + #n, '' ) +
'drop table [' + schema_name(schema_id) + '].[' + name + ']'
from sys.tables
-- user defined types
select #stmt = isnull( #stmt + #n, '' ) +
'drop type [' + schema_name(schema_id) + '].[' + name + ']'
from sys.types
where is_user_defined = 1
exec sp_executesql #stmt
Source: an Adam Anderson blog post
The best thing to do it is "Generate scripts for Drop"
Select Database -> Right Click -> Tasks -> Generate Scripts - will open wizard for generating scripts
after choosing objects in set Scripting option click Advanced Button
-> Set option 'Script to create' to true (want to create)
-> Set option 'Script to Drop' to true (want to drop)
-> Select the Check box to select objects wish to create script
-> Select the choice to write script (File, New window, Clipboard)
It includes dependent objects by default.(and will drop constraint at first)
Execute the script
This way we can customize our script.
To drop all tables:
exec sp_MSforeachtable 'DROP TABLE ?'
This will, of course, drop all constraints, triggers etc., everything but the stored procedures.
For the stored procedures I'm afraid you will need another stored procedure stored in master.
I'd do it in two statements: DROP DATABASE ???
and then CREATE DATABASE ???
I tried some of the script here, but they didn't work for me, as I have my tables in schemas. So I put together the following. Note that this script takes a list of schemas, and drops then in sequence. You need to make sure that you have a complete ordering in your schemas. If there are any circular dependencies, then it will fail.
PRINT 'Dropping whole database'
GO
------------------------------------------
-- Drop constraints
------------------------------------------
DECLARE #Sql NVARCHAR(500) DECLARE #Cursor CURSOR
SET #Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE ['+tc2.CONSTRAINT_SCHEMA+'].[' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN #Cursor FETCH NEXT FROM #Cursor INTO #Sql
WHILE (##FETCH_STATUS = 0)
BEGIN
PRINT #Sql
Exec (#Sql)
FETCH NEXT FROM #Cursor INTO #Sql
END
CLOSE #Cursor DEALLOCATE #Cursor
GO
------------------------------------------
-- Drop views
------------------------------------------
DECLARE #sql VARCHAR(MAX) = ''
, #crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;
SELECT #sql = #sql + 'DROP VIEW ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(v.name) +';' + #crlf
FROM sys.views v
PRINT #sql;
EXEC(#sql);
GO
------------------------------------------
-- Drop procs
------------------------------------------
PRINT 'Dropping all procs ...'
GO
DECLARE #sql VARCHAR(MAX) = ''
, #crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;
SELECT #sql = #sql + 'DROP PROC ' + QUOTENAME(SCHEMA_NAME(p.schema_id)) + '.' + QUOTENAME(p.name) +';' + #crlf
FROM [sys].[procedures] p
PRINT #sql;
EXEC(#sql);
GO
------------------------------------------
-- Drop tables
------------------------------------------
PRINT 'Dropping all tables ...'
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO
------------------------------------------
-- Drop sequences
------------------------------------------
PRINT 'Dropping all sequences ...'
GO
DECLARE #DropSeqSql varchar(1024)
DECLARE DropSeqCursor CURSOR FOR
SELECT DISTINCT 'DROP SEQUENCE ' + s.SEQUENCE_SCHEMA + '.' + s.SEQUENCE_NAME
FROM INFORMATION_SCHEMA.SEQUENCES s
OPEN DropSeqCursor
FETCH NEXT FROM DropSeqCursor INTO #DropSeqSql
WHILE ( ##FETCH_STATUS <> -1 )
BEGIN
PRINT #DropSeqSql
EXECUTE( #DropSeqSql )
FETCH NEXT FROM DropSeqCursor INTO #DropSeqSql
END
CLOSE DropSeqCursor
DEALLOCATE DropSeqCursor
GO
------------------------------------------
-- Drop Schemas
------------------------------------------
DECLARE #schemas as varchar(1000) = 'StaticData,Ird,DataImport,Collateral,Report,Cds,CommonTrade,MarketData,TypeCode'
DECLARE #schemasXml as xml = cast(('<schema>'+replace(#schemas,',' ,'</schema><schema>')+'</schema>') as xml)
DECLARE #Sql NVARCHAR(500) DECLARE #Cursor CURSOR
SET #Cursor = CURSOR FAST_FORWARD FOR
SELECT sql = 'DROP SCHEMA ['+schemaName+']' FROM
(SELECT CAST(T.schemaName.query('text()') as VARCHAR(200)) as schemaName FROM #schemasXml.nodes('/schema') T(schemaName)) as X
JOIN information_schema.schemata S on S.schema_name = X.schemaName
OPEN #Cursor FETCH NEXT FROM #Cursor INTO #Sql
WHILE (##FETCH_STATUS = 0)
BEGIN
PRINT #Sql
Exec (#Sql)
FETCH NEXT FROM #Cursor INTO #Sql
END
CLOSE #Cursor DEALLOCATE #Cursor
GO
This is what I have tried:
SELECT 'DROP TABLE [' + SCHEMA_NAME(schema_id) + '].[' + name + ']' FROM sys.tables
What ever the output it will print, just copy all and paste in new query and press execute.
This will delete all tables.
Back up a completely empty database. Instead of dropping all the objects, just restore the backup.
I accidentally ran a db init script against my master database tonight. Anyways, I quickly ran into this thread. I used the: exec sp_MSforeachtable 'DROP TABLE ?' answer, but had to execute it multiple times until it didn't error (dependencies.) After that I stumbled upon some other threads and pieced this together to drop all the stored procedures and functions.
DECLARE mycur CURSOR FOR select O.type_desc,schema_id,O.name
from
sys.objects O LEFT OUTER JOIN
sys.extended_properties E ON O.object_id = E.major_id
WHERE
O.name IS NOT NULL
AND ISNULL(O.is_ms_shipped, 0) = 0
AND ISNULL(E.name, '') <> 'microsoft_database_tools_support'
AND ( O.type_desc = 'SQL_STORED_PROCEDURE' OR O.type_desc = 'SQL_SCALAR_FUNCTION' )
ORDER BY O.type_desc,O.name;
OPEN mycur;
DECLARE #schema_id int;
DECLARE #fname varchar(256);
DECLARE #sname varchar(256);
DECLARE #ftype varchar(256);
FETCH NEXT FROM mycur INTO #ftype, #schema_id, #fname;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sname = SCHEMA_NAME( #schema_id );
IF #ftype = 'SQL_STORED_PROCEDURE'
EXEC( 'DROP PROCEDURE "' + #sname + '"."' + #fname + '"' );
IF #ftype = 'SQL_SCALAR_FUNCTION'
EXEC( 'DROP FUNCTION "' + #sname + '"."' + #fname + '"' );
FETCH NEXT FROM mycur INTO #ftype, #schema_id, #fname;
END
CLOSE mycur
DEALLOCATE mycur
GO
Try this
Select 'ALTER TABLE ' + Table_Name +' drop constraint ' + Constraint_Name from Information_Schema.CONSTRAINT_TABLE_USAGE
Select 'drop Procedure ' + specific_name from Information_Schema.Routines where specific_name not like 'sp%' AND specific_name not like 'fn_%'
Select 'drop View ' + table_name from Information_Schema.tables where Table_Type = 'VIEW'
SELECT 'DROP TRIGGER ' + name FROM sysobjects WHERE type = 'tr'
Select 'drop table ' + table_name from Information_Schema.tables where Table_Type = 'BASE TABLE'
In addition to #Ivan's answer, types all need to be included
/* Drop all Types */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sys.types where is_user_defined = 1 ORDER BY [name])
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP TYPE [dbo].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Type: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sys.types where is_user_defined = 1 AND [name] > #name ORDER BY [name])
END
GO
You have to disable all triggers and constraints first.
EXEC sp_MSforeachtable #command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"
EXEC sp_MSforeachtable #command1="ALTER TABLE ? DISABLE TRIGGER ALL"
After that you can generate the scripts for deleting the objects as
SELECT 'Drop Table '+name FROM sys.tables WHERE type='U';
SELECT 'Drop Procedure '+name FROM sys.procedures WHERE type='P';
Execute the statements generated.
try this with sql2012 or above,
this will help to delete all objects by selected schema
DECLARE #MySchemaName VARCHAR(50)='dbo', #sql VARCHAR(MAX)='';
DECLARE #SchemaName VARCHAR(255), #ObjectName VARCHAR(255), #ObjectType VARCHAR(255), #ObjectDesc VARCHAR(255), #Category INT;
DECLARE cur CURSOR FOR
SELECT (s.name)SchemaName, (o.name)ObjectName, (o.type)ObjectType,(o.type_desc)ObjectDesc,(so.category)Category
FROM sys.objects o
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
INNER JOIN sysobjects so ON so.name=o.name
WHERE s.name = #MySchemaName
AND so.category=0
AND o.type IN ('P','PC','U','V','FN','IF','TF','FS','FT','PK','TT')
OPEN cur
FETCH NEXT FROM cur INTO #SchemaName,#ObjectName,#ObjectType,#ObjectDesc,#Category
SET #sql='';
WHILE ##FETCH_STATUS = 0 BEGIN
IF #ObjectType IN('FN', 'IF', 'TF', 'FS', 'FT') SET #sql=#sql+'Drop Function '+#MySchemaName+'.'+#ObjectName+CHAR(13)
IF #ObjectType IN('V') SET #sql=#sql+'Drop View '+#MySchemaName+'.'+#ObjectName+CHAR(13)
IF #ObjectType IN('P') SET #sql=#sql+'Drop Procedure '+#MySchemaName+'.'+#ObjectName+CHAR(13)
IF #ObjectType IN('U') SET #sql=#sql+'Drop Table '+#MySchemaName+'.'+#ObjectName+CHAR(13)
--PRINT #ObjectName + ' | ' + #ObjectType
FETCH NEXT FROM cur INTO #SchemaName,#ObjectName,#ObjectType,#ObjectDesc,#Category
END
CLOSE cur;
DEALLOCATE cur;
SET #sql=#sql+CASE WHEN LEN(#sql)>0 THEN 'Drop Schema '+#MySchemaName+CHAR(13) ELSE '' END
PRINT #sql
--EXECUTE (#sql)
Here I found new query to delete all sp,functions and triggers
declare #procName varchar(500)
declare cur cursor
for select [name] from sys.objects where type = 'p'
open cur
fetch next from cur into #procName
while ##fetch_status = 0
begin
exec('drop procedure ' + #procName)
fetch next from cur into #procName
end
close cur
deallocate cur
To add to Ivan's answer, I have also had the need to drop all user-defined types, so I have added this to the script:
/* Drop all user-defined types */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (select TOP 1 [name] from sys.types where is_user_defined = 1)
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP TYPE [dbo].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Type: ' + #name
SELECT #name = (select TOP 1 [name] from sys.types where is_user_defined = 1)
END
GO
To remove all objects in oracle :
1) Dynamic
DECLARE
CURSOR IX IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE ='TABLE'
AND OWNER='SCHEMA_NAME';
CURSOR IY IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE
IN ('SEQUENCE',
'PROCEDURE',
'PACKAGE',
'FUNCTION',
'VIEW') AND OWNER='SCHEMA_NAME';
CURSOR IZ IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TYPE') AND OWNER='SCHEMA_NAME';
BEGIN
FOR X IN IX LOOP
EXECUTE IMMEDIATE('DROP '||X.OBJECT_TYPE||' '||X.OBJECT_NAME|| ' CASCADE CONSTRAINT');
END LOOP;
FOR Y IN IY LOOP
EXECUTE IMMEDIATE('DROP '||Y.OBJECT_TYPE||' '||Y.OBJECT_NAME);
END LOOP;
FOR Z IN IZ LOOP
EXECUTE IMMEDIATE('DROP '||Z.OBJECT_TYPE||' '||Z.OBJECT_NAME||' FORCE ');
END LOOP;
END;
/
2)Static
SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS;' FROM user_tables
union ALL
select 'drop '||object_type||' '|| object_name || ';' from user_objects
where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION')
union ALL
SELECT 'drop '
||object_type
||' '
|| object_name
|| ' force;'
FROM user_objects
WHERE object_type IN ('TYPE');
One more sample
declare #objectId int, #objectName varchar(500), #schemaName varchar(500), #type nvarchar(30), #parentObjId int, #parentObjName nvarchar(500)
declare cur cursor
for
select obj.object_id, s.name as schema_name, obj.name, obj.type, parent_object_id
from sys.schemas s
inner join sys.sysusers u
on u.uid = s.principal_id
JOIN
sys.objects obj on obj.schema_id = s.schema_id
WHERE s.name = 'schema_name' and (type = 'p' or obj.type = 'v' or obj.type = 'u' or obj.type = 'f' or obj.type = 'fn')
order by obj.type
open cur
fetch next from cur into #objectId, #schemaName, #objectName, #type, #parentObjId
while ##fetch_status = 0
begin
if #type = 'p'
begin
exec('drop procedure ['+#schemaName +'].[' + #objectName + ']')
end
if #type = 'fn'
begin
exec('drop FUNCTION ['+#schemaName +'].[' + #objectName + ']')
end
if #type = 'f'
begin
set #parentObjName = (SELECT name from sys.objects WHERE object_id = #parentObjId)
exec('ALTER TABLE ['+#schemaName +'].[' + #parentObjName + ']' + 'DROP CONSTRAINT ' + #objectName)
end
if #type = 'u'
begin
exec('drop table ['+#schemaName +'].[' + #objectName + ']')
end
if #type = 'v'
begin
exec('drop view ['+#schemaName +'].[' + #objectName + ']')
end
fetch next from cur into #objectId, #schemaName, #objectName, #type, #parentObjId
end
close cur
deallocate cur
Seems like a rather dangerous feature to me. If you'd implement something like this I would make sure to properly secure it in a way you won't be able to run this per accident.
As suggested before you could make some sort of stored procedure yourself.
In SQL Server 2005 you could have a look this system table to determine and find the objects you would like to drop.
select * from sys.objects
DECLARE #name VARCHAR(255)
DECLARE #type VARCHAR(10)
DECLARE #prefix VARCHAR(255)
DECLARE #sql VARCHAR(255)
DECLARE curs CURSOR FOR
SELECT [name], xtype
FROM sysobjects
WHERE xtype IN ('U', 'P', 'FN', 'IF', 'TF', 'V', 'TR') -- Configuration point 1
ORDER BY name
OPEN curs
FETCH NEXT FROM curs INTO #name, #type
WHILE ##FETCH_STATUS = 0
BEGIN
-- Configuration point 2
SET #prefix = CASE #type
WHEN 'U' THEN 'DROP TABLE'
WHEN 'P' THEN 'DROP PROCEDURE'
WHEN 'FN' THEN 'DROP FUNCTION'
WHEN 'IF' THEN 'DROP FUNCTION'
WHEN 'TF' THEN 'DROP FUNCTION'
WHEN 'V' THEN 'DROP VIEW'
WHEN 'TR' THEN 'DROP TRIGGER'
END
SET #sql = #prefix + ' ' + #name
PRINT #sql
EXEC(#sql)
FETCH NEXT FROM curs INTO #name, #type
END
CLOSE curs
DEALLOCATE curs
try this....
USE DATABASE
GO
DECLARE #tname VARCHAR(150)
DECLARE #strsql VARCHAR(300)
SELECT #tname = (SELECT TOP 1 [name] FROM sys.objects WHERE [type] = 'U' and [name] like N'TableName%' ORDER BY [name])
WHILE #tname IS NOT NULL
BEGIN
SELECT #strsql = 'DROP TABLE [dbo].[' + RTRIM(#tname) +']'
EXEC (#strsql)
PRINT 'Dropped Table : ' + #tname
SELECT #tname = (SELECT TOP 1 [name] FROM sys.objects WHERE [type] = 'U' AND [name] like N'TableName%' AND [name] > #tname ORDER BY [name])
END
There is no single statement that can be used to achieve this aim.
You could of course create yourself a stored procedure that you could use to perform these various administrative tasks.
You could then execute the procedure using this single statement.
Exec sp_CleanDatabases #DatabaseName='DBname'