We had a MS SQL database in which one audit table grew big to 5TB (due to an oversight). We identified unwanted records from this audit table and have deleted these records from this table. Now the total size of the tables and indexes is about 20GB, however the data and log file size still stays at 5TB. After looking through various forums, i found that we can reduce the data and log file size using
DBCC SHRINKFILE(N'datafile', 0);
DBCC SHRINKFILE(N'logfile', 0);
Followed by reorganize all indexes
SELECT 'ALTER INDEX '+indexname+' ON '+tablename+' REORGANIZE;'
from
(
SELECT
dbschemas.[name]+'.'+dbtables.[name] as tablename,
dbindexes.[name] as indexname,
indexstats.avg_fragmentation_in_percent,
indexstats.page_count [pages]
FROM
sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables
on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas
on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes
ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE
indexstats.database_id = DB_ID()
AND indexstats.avg_fragmentation_in_percent >= 5.0
AND indexstats.page_count > 1
) a;
Is this a good approach to reduce the database size? I have came across blog posts suggesting not to shrink the db files. Any suggestions and pointers in the right direction will be of help. Thanks in Advance