Click here to Skip to main content
15,888,802 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have more than 50 databases in server

how to backup all the databases form the sql server 2008 R2.

Thanks ,
Posted

This script will give you a list of databases

SQL
SELECT name, database_id, create_date
FROM sys.databases ;
GO


This will backup a database:

BACKUP DATABASE AdventureWorks2012 TO DISK='d:\adw.bak'


I don't know if you can use a select to do multiple backups, but if all else fails, you could use a CURSOR and 'EXEC' to create and run SQL that backs up all your databases.

Actually, the easy way is to run this:

SQL
select 'BACKUP DATABASE ' + NAME + ' TO DISK=''d:\' + NAME + '.bak'''
from sys.databases;



which will create a table full of the backup commands you need. Then you can just run them, one by one, or in sequence, in Management Studio or in a proc.
 
Share this answer
 
v2
Comments
King Fisher 26-Dec-13 1:15am    
this is okay for backup a single database .but how to do more than 1 database?
Christian Graus 26-Dec-13 1:40am    
Read my answer again. You can LIST all the databases using the SQL I gave you. You can use the DB name to form a file name as well. I don't know if you can do a BACKUP inside a select ( I doubt it ), but I bet you can write code to form the SQL to back up each database, using a cursor, then use EXEC to execute each line in turn to back up each database.

Just a sec, let me show you something.
King Fisher 26-Dec-13 3:42am    
thanks for your timing..i solved this
Christian Graus 26-Dec-13 5:26am    
Yes, you did what I told you to :-) Normally I would test SQL before I give it to people, but I had no intention of waiting for all my DBs to back up.
Christian Graus 26-Dec-13 5:27am    
I suspect your solution will not work if a database has been deleted, you should add code to check if @db_name is null, which it will be, in that case.
SQL
declare @db_name as nvarchar(max);
declare @id as int;
declare @end_id as int;
declare @filename as nvarchar(max);
begin
select @id=1
select @end_id= max(database_id) from sys.databases
while(@id < @end_id)
begin
select @db_name=name from sys.databases  where database_id=@id
set @filename='D:\BK\'+@db_name+'.bak'
backup database @db_name to disk =@filename;
set @id=@id+1
end
end
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900