Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to select all databases then run another query on the result

*******EDITED*****

I have multiple sql servers with around 200-300 dbs in them and want to save space on my server.


I would like to run a shrink routine on all databases in my sql server by running this script through a task scheduler. I have the queries but I do not know how to connect the two together. For selecting all databases I use this

select * from sys.sysdatabases
Where name <> 'master' and name <> 'tempdb' and name <> 'model' and name <> 'msdb'

For my shrink routeen I use this

USE [single_database_name]
GO
DBCC SHRINKFILE ('single_database_name', 10)
GO

How can I connect the two queries so that the "single_database_name" is coming from the list of all database names from the first query.

Thanks for your help

like image 438
WillNZ Avatar asked Dec 08 '25 21:12

WillNZ


2 Answers

Use a cursor with dynamic SQL. This will shrink each file individually on each database.

Declare @dataFiles Table (databaseName Varchar(256), datafile Varchar(256))
Declare @SQL Nvarchar(Max), @databaseName Varchar(256), @dbfile Varchar(256)

Insert  @dataFiles
select  sd.name, smf.name
from    sys.sysdatabases sd
join    sys.master_files smf
        On  sd.[dbid] = smf.database_id
Where   sd.name not in ('master','tempdb','model','msdb')

Declare cur Cursor For      
Select  databaseName,
        datafile
From    @dataFiles

Open    cur
Fetch   Next 
From    cur
Into    @databaseName,
        @dbfile

While   @@Fetch_Status = 0
Begin
        Set     @SQL = 'USE [' + @databasename + ']
                        DBCC SHRINKFILE (''' + @dbfile + ''', 10) WITH NO_INFOMSGS'

        Exec    sp_executeSQL @SQL

        Fetch   Next 
        From    cur
        Into    @databaseName,
                @dbfile
End
Close   cur
Deallocate cur

select  sd.name As DatabaseName, smf.name DBFileName, (size*8)/1024 SizeMB
from    sys.sysdatabases sd
join    sys.master_files smf
        On  sd.[dbid] = smf.database_id
Where   sd.name not in ('master','tempdb','model','msdb')
like image 163
Eric J. Price Avatar answered Dec 10 '25 09:12

Eric J. Price


select 
'USE '+ quotename([name]) + '
GO
DBCC SHRINKFILE (''' + [name] + ''', 10)
GO
'
from sys.databases
where name not in ('master', 'tempdb', 'model', 'msdb')

But please don't do this: shrinking is bad.

like image 30
Ben Thul Avatar answered Dec 10 '25 10:12

Ben Thul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!