This blog is a repository of my experiences and knowledge in SharePoint Development and Management.
Thursday, May 30, 2013
Wednesday, May 29, 2013
How to SHRINKFILE and TRUNCATEFILE in SQL Server 2008.
http://www.codeproject.com/Articles/261132/Truncate-Shrink-Transaction-Log-files-on-SQL-Serve
Updated working Script
Updated working Script
--Step1--
CREATE TABLE #TransactionLogFiles (DatabaseName VARCHAR(150), LogFileName VARCHAR(150))
INSERT INTO #TransactionLogFiles (DatabaseName, LogFileName)
SELECT b.[name], a.[name]FROM sys.master_files a
JOIN sys.databases b
ON a.database_id = b.database_id
WHERE a.[type] = 1 AND b.[name] NOT IN ('master','tempdb','model','msdb')
--Step 2 --
DECLARE @DataBase VARCHAR(128)
DECLARE @SqlScript VARCHAR(MAX)
-- step 2. insert all the database name and corresponding log files' names into the temp table
DECLARE DataBaseList CURSOR FOR
SELECT DatabaseName, LogFileName FROM #TransactionLogFiles
OPEN DataBaseList FETCH
NEXT FROM DataBaseList INTO @DataBase
WHILE @@FETCH_STATUS <> -1
BEGIN
SET @SqlScript = 'USE [' + @DataBase + '] INSERT INTO #TransactionLogFiles(DatabaseName, LogFileName) SELECT '''
+ @DataBase + ''', Name FROM sysfiles WHERE FileID=2'
--SELECT @SqlScript
EXEC(@SqlScript)
FETCH NEXT FROM DataBaseList INTO @DataBase END
DEALLOCATE DataBaseList
--Step 3 --
SET @SqlScript = ''
DECLARE TransactionLogList CURSOR FOR
SELECT DatabaseName, LogFileName FROM #TransactionLogFiles
DECLARE @LogFile VARCHAR(128)
OPEN TransactionLogList FETCH
NEXT FROM TransactionLogList INTO @DataBase, @LogFile
WHILE @@FETCH_STATUS <> -1
BEGIN
SELECT @SqlScript = @SqlScript + 'USE [' + @DataBase + '] '
+ 'ALTER DATABASE [' + @DataBase + '] SET RECOVERY SIMPLE WITH NO_WAIT '
+ 'DBCC SHRINKFILE(N''' + @LogFile + ''', 1) '
+ 'ALTER DATABASE [' + @DataBase + '] SET RECOVERY FULL WITH NO_WAIT '
FETCH NEXT FROM TransactionLogList INTO @DataBase, @LogFile END
DEALLOCATE TransactionLogList
EXEC(@SqlScript)
-- step 4. clean up
DROP TABLE #TransactionLogFiles
Labels:
c drive,
clear,
data folder,
shrinkfile,
space,
SQL,
truncatefile
Subscribe to:
Posts (Atom)