A Tech Log

April 1, 2009

TSQL to Shrink All Databases on a Server

Filed under: Development — adallow @ 3:44 pm
Tags: ,
DECLARE @name varchar(500)
DECLARE @sql varchar(8000)
SET @sql = ”
DECLARE Database_Cursor CURSOR READ_ONLY FOR
SELECT Name
FROM sysdatabases
WHERE DBID > 4
OPEN Database_Cursor
FETCH NEXT FROM Database_Cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = @sql + ‘backup log [‘ + @name + ‘] with truncate_only’ + CHAR(10)
SET @sql = @sql +  ‘dbcc SHRINKDATABASE ( [‘ + @name + ‘] )’ + CHAR(10)

FETCH NEXT FROM Database_Cursor INTO @name

END
CLOSE Database_Cursor
DEALLOCATE Database_Cursor


print @sql

EXEC(@sql)

Advertisements

Blog at WordPress.com.