Script – Generate DBCC ShrinkFile for each datbase files

You can use below query to generate DBCC Shrikfile command for data and log file. Next step you have to copy the output from the result windows & execute it.

Query

select 'use ' + db_name(dbid) + char(13) + 'dbcc shrinkfile (' + quotename(sf.name,'''') + ' ,truncateonly)' from sysaltfiles sf
inner join sys.databases sd on sf.dbid = sd.database_id
where state_desc = 'online'

 

Comments

4 responses to “Script – Generate DBCC ShrinkFile for each datbase files”

  1. paul s Avatar
    paul s

    There was a missing “sys” in your select for sys.sysaltfiles table. Here is the corrected syntax.
    –Generate DBCC SHRINKFILE commands
    select ‘use ‘ + db_name(dbid) + char(13) + ‘dbcc shrinkfile (‘ + quotename(sf.name,””) + ‘ ,truncateonly)’
    from sys.sysaltfiles sf
    inner join sys.databases sd on sf.dbid = sd.database_id
    where state_desc = ‘online’

    1. Jugal Shah Avatar

      thanks, I haven’t add sys because it can work with SQL 2000 as well.

  2. Andrey Avatar
    Andrey

    How to run this command?

    1. Jugal Shah Avatar

      Hi Andrey, you have to copy the result of the query & execute it.

Thanks for the comment, will get back to you soon… Jugal Shah