Are cursors/While loops the only way to make administrative changes to multiple databases?
6
votes
2
answers
1375
views
I specifically want a programmable way to change the recovery model of all the databases on a server, and i know this solution can be applied to all 'Alter Database' commands. While I know SMO in PowerShell can solve this problem very easily:
Import-Module SQLPS
CD SQL\*ServerName*\*InstanceName*\databases
foreach ($database in (ls -force)){
$database.recoverymodel = 'Full'
$database.update
}
I'm looking for the most efficient T-SQL solution.
It has been ingrained in my head to avoid cursors at all costs, however I can't think of a set based solution to perform alter statements.
Here is the cursor based solution.
DECLARE @sql varchar(MAX), @name varchar(50)
DECLARE cur CURSOR FOR
SELECT name
FROM sys.databases
where name 'tempdb';
OPEN cur
FETCH NEXT FROM cur
INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER DATABASE ' + @name + ' SET RECOVERY FULL;'
exec(@sql)
FETCH NEXT FROM cur INTO @name
END
CLOSE CUR
DEALLOCATE cur
1. This can also be done with a while loop, but that solution still goes through a looping process... do while loops offer significantly better performance?
2. Am i being paranoid about performance? I say that because administrative tasks such as this aren't done very often, and there generally isn't a massive amount of objects you need to loop through. However i always think "What if i worked in a large environment with thousands of objects" and then i begin to feel guilty that I may not be using the most efficient solution.
Asked by Luke Pafford
(311 rep)
May 1, 2016, 08:39 AM
Last activity: May 1, 2016, 09:54 PM
Last activity: May 1, 2016, 09:54 PM