Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script to delete all non-system objects in SQL Server 2008

Does anyone have a script that will delete all non-system tables/procs/views from a database?

I created some views, procs and tables which I need to clean up and doing them individually is too cumbersome.

like image 343
femi Avatar asked Dec 21 '10 12:12

femi


People also ask

How do I remove all objects from a schema in SQL Server?

SQL Server have some built-in schema, for example : dbo, guest, sys, and INFORMATION_SCHEMA which cannot be deleted. Syntax : DROP SCHEMA [IF EXISTS] schema_name; Note : Delete all objects from the schema before dropping the schema.

How do I remove a dependencies from a table in SQL?

Right-click a database in SQL Server Object Explorer, and select Delete. Accept all the default settings in the Delete Database dialog, and click OK.

Which command is used to delete the DB objects?

DROP is used to delete a whole database or just a table. The DROP statement destroys the objects like an existing database, table, index, or view. A DROP statement in SQL removes a component from a relational database management system (RDBMS).


2 Answers

You could always query your system catalog views and have it generate the necessary DROP statements:

SELECT 'DROP PROCEDURE [' + SCHEMA_NAME(schema_id) + '].[' + pr.NAME +']'
FROM sys.procedures pr
WHERE pr.is_ms_shipped = 0

UNION

SELECT 'DROP VIEW [' + SCHEMA_NAME(schema_id) + '].[' + v.NAME + ']'
FROM sys.views v
WHERE v.is_ms_shipped = 0

UNION

SELECT 'ALTER TABLE [' + SCHEMA_NAME(schema_id) + '].[' + OBJECT_NAME(fk.parent_object_ID) + '] DROP CONSTRAINT ' + fk.name 
FROM sys.foreign_keys fk
WHERE is_ms_shipped = 0

UNION

SELECT 'DROP TABLE [' + SCHEMA_NAME(schema_id) + '].[' + t.NAME + ']'
FROM sys.tables t
WHERE t.is_ms_shipped = 0

This will generate a long list of DROP ..... statements, just copy & paste those into a new SSMS window and execute them.

like image 159
marc_s Avatar answered Nov 16 '22 00:11

marc_s


Wouldn't it be easier to drop/recreate the database?

DROP DATABASE yourdbname
CREATE DATABASE yourdbname
like image 26
Klaus Byskov Pedersen Avatar answered Nov 15 '22 23:11

Klaus Byskov Pedersen