SQL Server:备份所有数据库

时间:2012-05-22 09:57:16

标签: sql sql-server-2008 tsql backup

我想知道是否有任何方法可以定期将整个SQL Server(我们正在使用SQL Server 2008)备份到特定位置。我知道我们能够备份单个特定的数据库但是为了便于使用而且每次我想要一个新数据库时都不需要设置备份,有没有办法做到这一点?

但是,如果有的话,我必须能够轻松地从该服务器备份中恢复单个数据库,就好像我已经单独备份它们一样。

使用的方法只是一个纯粹的备份而不是差异,所以不必担心并发症。

2 个答案:

答案 0 :(得分:3)

您可以运行以下脚本,只需将@path变量更改为您要存储数据库的位置。

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 

SET @path = 'C:\Backup\'  

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')  

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

获取:

http://www.mssqltips.com/sqlservertip/1070/simple-script-to-backup-all-sql-server-databases/

答案 1 :(得分:1)

考虑备份隐藏资源数据库

Use master
GO

--enable
sp_configure 'show advanced options'
GO
/* 0 = Disabled , 1 = Enabled */
sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE WITH OVERRIDE
GO


--===Resource file details
SELECT 'ResourceDB' AS 'Database Name'
    , NAME AS [Database File]
    , FILENAME AS [Database File Location] 
FROM sys.sysaltfiles 
    WHERE DBID = 32767
ORDER BY [Database File]
GO

--===Copy resource files
DECLARE @ResDataFile VARCHAR(1000), @ResLogFile VARCHAR(1000)
SELECT 
    @ResDataFile = CASE NAME WHEN  'Data' THEN FILENAME ELSE @ResDataFile END,
    @ResLogFile = CASE NAME WHEN 'Log' THEN FILENAME ELSE @ResLogFile END
FROM sys.sysaltfiles 
WHERE DBID = 32767

SELECT @ResDataFile, @ResLogFile

DECLARE @cmd VARCHAR(1000)

--===Copy data file
SELECT @cmd = 'COPY /Y "' + @ResDataFile + '" "G:\SQLBackups"'
--PRINT @cmd
EXEC xp_cmdshell @cmd

--===Copy log file
SELECT @cmd = 'COPY /Y "' + @ResLogFile + '" "G:\SQLBackups"'
--PRINT @cmd
EXEC xp_cmdshell @cmd

GO
--Disable
sp_configure 'show advanced options'
GO
/* 0 = Disabled , 1 = Enabled */
sp_configure 'xp_cmdshell', 0
GO
RECONFIGURE WITH OVERRIDE
GO