Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to backup all databases on SQL Server 2008

I have been working on SQL Server 2008 R2 for 4 years and it's time to format my laptop.

I just use the default instance, which I can access using the . as server name, and then my username and password for user authentication.

Now I want to format my laptop, and it is almost impossible to backup manually all the database.

I found in the following path

C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL

all the databases that I have, for each database I found:

  1. databasename_log.ldf
  2. databasename.mdf

I copied these files to an external hard drive.

My question:

Are those files enough to import the database after formatting? Will they work if I installed (after formatting) SQL Server 2012 not 2008 R2?

like image 471
Marco Dinatsoli Avatar asked Jul 05 '26 03:07

Marco Dinatsoli


1 Answers

I found the SQL from this article useful in taking backups of all databases on a server.

DECLARE @name VARCHAR(50) -- database name  
DECLARE @path VARCHAR(256) -- path for backup files  
DECLARE @fileName VARCHAR(256) -- filename for backup  
DECLARE @fileDate VARCHAR(20) -- used for file name


-- specify database backup directory
SET @path = 'C:\Backup\'  


-- specify filename format
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) 


DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM master.dbo.sysdatabases 
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases


OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   


WHILE @@FETCH_STATUS = 0   
BEGIN   
       SET @fileName = @path + @name + '_' + @fileDate + '.BAK'  
       BACKUP DATABASE @name TO DISK = @fileName  


       FETCH NEXT FROM db_cursor INTO @name   
END   


CLOSE db_cursor   
DEALLOCATE db_cursor
like image 163
Sathish Avatar answered Jul 06 '26 17:07

Sathish



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!