Friday, June 21, 2013

Query for Delete All tables,procedures,views,function from database in SQL Server

==>> In this article I am posting SQL Query for Delete All tables,procedures,views,function from database in SQL Server. Some time we need to Delete All tables,procedures,views,function from database in SQL Server so this query will heplfull.



 --For Delete Tables

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

--For Delete Procedures
GO
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
        IF @procName <> 'DeleteAllProcedures'
            EXEC('drop procedure ' + @procName)
        FETCH NEXT FROM cur INTO @procName
    END

CLOSE cur
DEALLOCATE cur


--For Delete Views

GO
DECLARE @procName VARCHAR(500)
DECLARE cur CURSOR
FOR SELECT [name] FROM sys.objects WHERE type = 'v'
OPEN cur

FETCH NEXT FROM cur INTO @procName
WHILE @@fetch_status = 0
    BEGIN
        EXEC('drop view ' + @procName)
        FETCH NEXT FROM cur INTO @procName
    END
CLOSE cur
DEALLOCATE cur



--For Delete functions
GO
DECLARE @procName VARCHAR(500)
DECLARE cur CURSOR
FOR SELECT [name] FROM sys.objects WHERE type = 'fn'
OPEN cur

FETCH NEXT FROM cur INTO @procName
WHILE @@fetch_status = 0
    BEGIN
        EXEC('drop function ' + @procName)
        FETCH NEXT FROM cur INTO @procName
    END

CLOSE cur
DEALLOCATE cur

No comments:

Post a Comment