Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 227
  • Last Modified:

stored proc to backup a list of databases

I would like to create a stored procedure that will take a list of databases which I will supply upon execution, that will run a full backup.  I'm having trouble with getting it to loop through my list.
0
navajo26354
Asked:
navajo26354
1 Solution
 
Surendra NathCommented:
check this out

declare @T TABLE
(
dbNames VARCHAR(100)
,backupPath VARCHAR(1000)
)
INSERT INTO @T VALUES('DB1')
INSERT INTO @T VALUES('DB2')

INSERT INTO @T VALUES('DB3')
INSERT INTO @T VALUES('DB4')

DECLARE @DbName VARCHAR(100)
DECLARE @BackupPath VARCHAR(1000)
DECLARE @SQL VARCHAR(1000)
DECLARE T CURSOR
FOR 
SELECT dbNames FROM @T

OPEN T
FETCH T INTO @dbName,@BackupPath

WHILE @@FETCH_STATUS = 0 
BEGIN
SET @BackupPath = @BackupPath + @dbName + '.bak'
SET @SQL = 'del '+@BackupPath
exec xp_cmdshell @SQL
SET @SQL = 'backup database ' + @dbName + ' to disk = ' + '''' + @BackupPath + ''''
exec(@SQL)

FETCH T INTO @dbName,@BackupPath
END
CLOSE T
DEALLOCATE T

Open in new window

0
 
Aneesh RetnakaranDatabase AdministratorCommented:
try the solution mentioned here

http://ola.hallengren.com/
0
 
David ToddSenior DBACommented:
Hi,

Second Ola's script that Aneesh mentions above. As in why write your own when Ola's does nearly everything I can think of and then some!

Regards
  David

PS From someone who in the past has written their own scripts and restore jobs for test environments ...
0
 
Scott PletcherSenior DBACommented:
I use a table to control rebuilds instead of passing in a list or using Ola's code.

That allows a much more customized approach WITHOUT constantly having to change code, such as calling Ola's procedures.  It also allows significant changes to the backup process to be made quickly and easily just by UPDATEing the table, again instead of having to write or alter code.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now