如何在单个查询中创建所有数据库备份

时间:2017-02-02 06:51:30

标签: sql sql-server

如何为其SQL Server实例上提供的所有数据库创建备份文件。

1 个答案:

答案 0 :(得分:0)

如果有人想为其SQL Server实例上提供的所有数据库创建备份文件,则可以使用此存储过程。

您必须在某处创建此存储过程并将路径提供给您要存储所有.bak文件的路径

-- Use code for creating all database backup
USE [master]
GO

CREATE PROCEDURE [dbo].[CreateDBBackup] --create this sp somewhere in your SQL Server
AS
BEGIN
    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 location
    SET @path = 'D:\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')     

    OPEN db_cursor  

    FETCH NEXT FROM db_cursor INTO @name  

    WHILE @@FETCH_STATUS = 0  
    BEGIN  
        SET @fileName = @path + @name + '.BAK' 

        BACKUP DATABASE @name TO DISK = @fileName  

        FETCH NEXT FROM db_cursor INTO @name  
    END  

    CLOSE db_cursor  
    DEALLOCATE db_cursor
END