0% found this document useful (0 votes)
110 views

SQL Script To Shrink A File (Data or Log) in Chunks

This SQL script shrinks a database file (data or log) in chunks to avoid performance issues. It takes the database name, logical file name, and chunk size as parameters. It uses cursors to identify the target file, calculate the current and desired sizes, and repeatedly shrink the file in chunks with DBCC SHRINKFILE until it reaches the desired size.

Uploaded by

Gopal Indla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

SQL Script To Shrink A File (Data or Log) in Chunks

This SQL script shrinks a database file (data or log) in chunks to avoid performance issues. It takes the database name, logical file name, and chunk size as parameters. It uses cursors to identify the target file, calculate the current and desired sizes, and repeatedly shrink the file in chunks with DBCC SHRINKFILE until it reaches the desired size.

Uploaded by

Gopal Indla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

SQL Script to shrink a file (data or log) in chunks

--Script-2-TSQL Script to shrink a particular file (data or log) in chunks


--Need to give 3 parameters: DBName, Logical File Name, Chunk Size.

use DBName -- Change the DBName here.


go
checkpoint
go

DECLARE @Fileid INT, @chunkSize INT


DECLARE @flSize DECIMAL(18,2), @spFree DECIMAL(18,2), @ActSize INT, @bufSpace INT
DECLARE @flName VARCHAR(100), @SQLstr VARCHAR(1000)
DECLARE @logicalfilename VARCHAR(100)

-- sp_helpfile
set @logicalfilename = 'put_logical_filename'

SET @chunkSize = 500 -- No of MB to be shrunk in chunks.


SELECT * from sysfiles
DECLARE cur_SHRINK CURSOR FOR
SELECT Fileid, Name,
CAST((SIZE * 8 / 1024.0) AS DECIMAL(18,2)) AS FILESIZE,
CAST((SIZE * 8 / 1024.0) - (FILEPROPERTY(Name,'SpaceUsed')/ 128.0) AS DECIMAL(15,2)) SPACEFREE
FROM SYSFILES
WHERE name = @logicalfilename
OPEN cur_SHRINK

FETCH NEXT FROM cur_SHRINK


INTO @Fileid, @flName, @flSize, @spFree

WHILE @@FETCH_STATUS = 0
BEGIN
SET @ActSize = @flSize
SET @bufSpace = @flSize - @spFree + ((@flSize - @spFree)* 0.10)

PRINT RTRIM(@flName) + '...'


WHILE @ActSize > @bufSpace
BEGIN
SET @ActSize = @ActSize - @chunkSize
IF @ActSize < @bufSpace
SET @ActSize = @bufSpace
SET @SQLstr = 'DBCC SHRINKFILE(' + CAST(@Fileid AS VARCHAR) + ',' + CAST(@ActSize AS VARCHAR) + ')'
PRINT @SQLstr
EXEC(@SQLstr)
END

FETCH NEXT FROM cur_SHRINK


INTO @Fileid, @flName, @flSize, @spFree
END

CLOSE cur_SHRINK
DEALLOCATE cur_SHRINK

You might also like