﻿DECLARE @sql NVARCHAR(max)=''

--dropping views
SET @sql = '';

SELECT @sql += ' Drop view ' + QUOTENAME(s.NAME) + '.' + QUOTENAME(v.NAME) + '; '
FROM sys.views v
JOIN sys.schemas s
    ON v.[schema_id] = s.[schema_id]
WHERE  v.is_ms_shipped = 0

EXEC sp_executesql @sql

--dropping foreign keys
SET @sql = '';
SELECT @sql += 'Alter table ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ' drop constraint ' + QUOTENAME(fk.name) +'; '
FROM sys.foreign_keys AS fk
JOIN sys.tables AS t
    ON t.object_id = fk.parent_object_id
JOIN sys.schemas AS s
    ON s.schema_id = t.schema_id

Exec sp_executesql @sql

--dropping prinary and unique keys
SET @sql = '';
SELECT @sql += 'Alter table ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ' drop constraint ' + QUOTENAME(kc.name) +'; '
FROM sys.key_constraints AS kc
JOIN sys.tables AS t
    ON t.object_id = kc.parent_object_id
JOIN sys.schemas AS s
    ON s.schema_id = t.schema_id

EXEC sp_executesql @sql

--dropping tables
SET @sql = '';
SELECT @sql += ' Drop table ' + QUOTENAME(s.NAME) + '.' + QUOTENAME(t.NAME) + '; '
FROM sys.tables AS t
JOIN sys.schemas AS s
    ON t.[schema_id] = s.[schema_id]
WHERE  t.type = 'U'

EXEC sp_executesql @sql

--removing application user
SET @sql = '';
SELECT @sql += 'drop user ' + QUOTENAME(p.name)
FROM sys.database_principals AS p
WHERE p.authentication_type = 2

EXEC sp_executesql @sql
