Wednesday, January 4, 2012

DROP all VIEWS, FUNCTIONS, PROCEDURES

DECLARE @obj TABLE ( id int identity, objname sysname, objtype sysname )
DECLARE @i int
      , @sql nvarchar(max)


INSERT INTO @obj ( objname, objtype )
          SELECT A.name
               , (case when A.type = 'V' then 'VIEW'
                       when A.type in ('FN','IF','TF') then 'FUNCTION'
                       when A.type = 'P' then 'PROCEDURE'
                       else '' end ) 
            FROM sysobjects A (NOLOCK)
           WHERE A.type IN ( 'V', 'FN', 'IF', 'TF', 'P' )
        ORDER BY (case A.type when 'V' then 3
                              when 'P' then 1
                              else 2 end )
               , A.name DESC

SELECT @i = max(id) FROM @obj

WHILE @i > 0
 BEGIN
   SELECT @sql = 'DROP ' + A.objtype + ' ' + A.objname
     FROM @obj A
    WHERE A.id = @i
   PRINT @sql
   SET @i = @i - 1
 END




This is one example where using a table variable and while loop on a relatively small set of data is preferred, simply because the "sysobjects" table will be mutating through the process of the loop. Could still get away with it in a cursor if locks and hints are properly applied, but I still prefer to avoid it when possible.

No comments:

Post a Comment