Tuesday, January 3, 2012

Drop All Views in SQL SERVER

This is a very common scenario while updating or replacing database in SQL SERVER, we might need to delete all the views in SQL SERVER database. But to delete one view at a times is a time consuming process if database is huge with lots of Views.

To Drop all views in SQL SERVER database use following

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






Submit this story to DotNetKicks

0 comments: