简单T-Sql备份所有数据库

       有的时候我们可以使用T-sql来完成一些看起来复杂又重复的工作.例如,备份所有数据库,你可以使用SSMS来完成,但那样会很累的.
使用下面这段script也可完成,把备份路径改成你的目标文件夹即可,当然你可以写个存储过程.

 

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 = 'D:\Backup\' 

SELECT @fileDate = replace(replace(replace(replace(CONVERT(char(16), getdate(), 120 ),'-',''),'
',''),':',''),' ','') 

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

希望本文对您有帮助.
Author:Petter Liu   http://wintersun.cnblogs.com/ 

你可能感兴趣的:(t-sql)