T-SQL: Don't Run This in a Production Environment

Here’s some code that I’m posting mainly for my future reference. I do not recommend running this anywhere near a production machine.

DECLARE @SQL  varchar(8000) -- if you use nvarchar for whack table names, change this to 4000
SET @SQL = ''
SELECT @SQL = @SQL + 'ALTER DATABASE ' + NAME + ' SET RECOVERY SIMPLE; ALTER DATABASE ' + NAME + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DBCC SHRINKDATABASE (' + NAME + '); ALTER DATABASE ' + NAME + ' SET MULTI_USER' + Char(13)
FROM MASTER..Sysdatabases where sid != 0x01

PRINT @SQL
EXEC (@SQL)

This code does the following to all non-system databases:
1. Sets the recover to simple (my log files were OOC).
2. Kicks out all users and sets the db to single user
3. Shrinks the database files
4. Sets the database back to multi-user

Chrissy is a PowerShell MVP who has worked in IT for nearly 20 years, and currently serves as a Sr. Database Engineer in Belgium. Always an avid scripter, she attended the Monad session at Microsoft’s Professional Developers Conference in Los Angeles back in 2005 and has worked and played with PowerShell ever since. Chrissy is currently pursuing an MS in Systems Engineering at Regis University and helps maintain RealCajunRecipes.com in her spare time. She holds a number of certifications, including those relating to SQL Server, SuSE Linux, SharePoint and network security. She recently became co-lead of the SQL PASS PowerShell Virtual Chapter. You can follow her on Twitter at @cl.

Posted in SQL Server

Leave a Reply

Your email address will not be published. Required fields are marked *

*