SQL Server 備份及還原與 Windows Azure Blob 儲存體服務

本主題所介紹的概念、考量和範例程式碼主要說明如何設定及寫入 SQL Server 備份至 Windows Azure Blob 儲存體服務以及從中還原。 本主題也會提供使用 Windows Azure Blob 服務來儲存 SQL Server 備份的優點摘要。

SQL Server 2012 SP1 CU2 所導入的這項功能可讓 SQL Server 直接備份及還原至 Windows Azure Blob 服務。 此功能可用來針對內部部署執行個體或執行主控環境 (例如 Windows Azure 虛擬機器) 的 SQL Server 執行個體備份 SQL Server 資料庫。 備份至雲端提供了許多優點,例如可用性、沒有限制的地理複寫異地儲存體,以及在雲端之間移轉資料的方便性。 在這個版本中,您可以使用 tsql 或 SMO 來發出 BACKUP 或 RESTORE 陳述式。 這個版本無法使用 SQL Server Management Studio 備份或還原精靈來備份至 Windows Azure Blob 儲存體服務或從中還原。

在 SQL Server 2012 SP1 CU4 中,支援使用 PowerShell 備份至 Windows Azure Blob 儲存體服務並且從中還原。 若要要求此更新,請參閱此知識庫文件 (機器翻譯)。 本主題的<範例>一節包含 PowerShell 指令碼。 如需管理多個備份的 PowerShell 指令碼,請參閱<Use PowerShell to Backup Multiple Databases to Windows Azure Blob Storage Service>。

針對 SQL Server 備份使用 Windows Azure Blob 服務的優點

  • 彈性、可靠且沒有限制的異地儲存體:將您的備份儲存在 Windows Azure Blob 服務上可能會成為一種方便、彈性且容易存取的異地選項。 針對您的 SQL Server 備份建立異地儲存體就像修改現有的指令碼/作業一樣簡單。 異地儲存體通常應該遠離實際執行資料庫位置,防止單一災害同時影響異地和實際執行資料庫位置。 透過選擇地理複寫 Blob 儲存體,您就可以在發生可能影響整個地區的災害時,獲得一層額外的保護。 此外,您可以隨時隨地取得備份,輕鬆地針對還原作業進行存取。

  • 備份封存:Windows Azure Blob 儲存體服務提供了較佳的替代方案,有效取代封存備份的常用磁帶選項。 磁帶儲存體可能需要實際運輸至異地設施並採取措施來保護媒體。 將您的備份儲存在 Windows Azure Blob 儲存體中,即可提供立即、高可用性且耐用的封存選項。

  • 沒有硬體管理的負擔:Windows Azure 服務不會產生任何硬體管理的負擔。 Windows Azure 服務會管理硬體並提供地理複寫以產生備援效果,防止硬體故障。

  • 目前,對於在 Windows Azure 虛擬機器中執行的 SQL Server 執行個體而言,備份至 Windows Azure Blob 儲存體服務可以透過建立附加磁碟來完成。 不過,您可以附加至 Windows Azure 虛擬機器的磁碟數目有所限制。 超大執行個體的限制為 16 個磁碟,而較小執行個體的限制則更低。 只要啟用直接備份至 Windows Azure Blob 儲存體的功能,您就可以忽略 16 個磁碟的限制。

    此外,目前儲存在 Windows Azure Blob 儲存體服務中的備份檔案可以直接提供給內部部署 SQL Server 或在 Windows Azure 虛擬機器中執行的其他 SQL Server 使用,完全不需要進行資料庫附加/卸離,或是下載並附加 VHD。

  • 成本效益:只有使用的服務才要付費。 成為符合成本效益的異地與備份封存選項。 如需詳細資訊和連結,請參閱<Windows Azure 計費考量>一節。

Windows Azure 計費考量:

了解 Windows Azure 儲存體成本可讓您預測在 Windows Azure 中建立和儲存備份的成本。 

Windows Azure 定價計算機可以協助您預估成本。

儲存體:費用是根據使用的空間收費,而計算方式採累進費率和備援等級計算。 如需詳細資料與最新資訊,請參閱定價詳細資料文章的<資料管理>一節。

資料傳輸:輸入 Windows Azure 的資料傳輸是免費的。 輸出傳輸則必須支付頻寬使用量的費用,計算方式是根據地區特定的累進費率計算。 如需詳細資料,請參閱<定價詳細資料>文章的資料傳輸一節。

需求、元件和概念

本節內容:

  • 安全性

  • 重要元件和概念簡介

  • Windows Azure Blob 儲存體服務

  • SQL Server 元件

  • 限制

  • 支援 Backup/Restore 陳述式

安全性

下面是備份至 Windows Azure Blob 儲存體服務或從中還原時的安全性考量和需求。

  • 建立 Windows Azure Blob 儲存體服務的容器時,我們建議您將存取權設定為 [私用]。 將存取權設定為 [私用] 可將存取對象限制為能夠提供必要資訊來驗證 Windows Azure 帳戶的使用者或帳戶。

    安全性注意事項安全性注意事項

    SQL Server 需要將 Windows Azure 帳戶名稱和存取金鑰驗證儲存在 SQL Server 認證中。 當 Windows Azure 帳戶執行備份或還原作業時,這項資訊就會用來驗證該帳戶。

  • 用來發出 BACKUP 或 RESTORE 命令的使用者帳戶應該位於擁有 Alter any credential 權限的 db_backup operator 資料庫角色中。

安裝的必要條件

  • 在 Azure 虛擬機器上執行的 SQL Server:如果您要將 SQL Server 安裝在 Windows Azure 虛擬機器上,請安裝 SQL Server 2012 SP1 CU2,或更新現有的執行個體。 若要向 Microsoft 客戶支援要求更新,請參閱這篇文章

  • SQL Server 內部部署:SQL Server 2012 SP1 CU2 或更新版本都包含這項功能。 若要向 Microsoft 客戶支援要求更新,請參閱這篇文章

重要元件和概念簡介

下列兩節將介紹 Windows Azure Blob 儲存體服務,以及備份至 Windows Azure Blob 儲存體服務或從中還原時使用的 SQL Server 元件。 為了備份至 Windows Azure Blob 儲存體服務或從中還原,請務必了解這些元件以及它們之間的互動方式。

建立 Windows Azure 帳戶是進行此程序的第一步。 SQL Server 會使用 Windows Azure storage account name 及其 access key 值來驗證、寫入及讀取 Blob 至儲存體服務。 SQL Server 認證會儲存這項驗證資訊並且在備份或還原作業期間使用。 如需建立儲存體帳戶和執行簡單還原的完整逐步解說,請參閱教學課程:使用 Windows Azure 儲存體服務進行 SQL Server 備份與還原

將儲存體帳戶對應至 SQL 認證

Windows Azure Blob 儲存體服務

儲存體帳戶:儲存體帳戶是所有儲存體服務的起點。 若要存取 Windows Azure Blob 儲存體服務,請先建立 Windows Azure 儲存體帳戶。 storage account name 及其 access key 屬性是向 Windows Azure Blob 儲存體服務及其元件驗證的必要項目。

容器:容器會提供一組 Blob 的群組,而且可以儲存不限數目的 Blob。 若要將 SQL Server 備份寫入 Windows Azure Blob 服務,您至少必須建立根容器。

Blob:任何類型和大小的檔案。 Windows Azure Blob 儲存體服務可以儲存的 Blob 類型有兩種:區塊和分頁 Blob。 SQL Server 備份會使用分頁 Blob 做為 Blob 類型。 您可以使用下列 URL 格式來定址 Blob:https://<儲存體帳戶>.blob.core.windows. net/<容器>/<Blob>

Azure BLOB 儲存

如需有關 Windows Azure Blob 儲存體服務的詳細資訊,請參閱如何使用 Windows Azure Blob 儲存體服務

如需有關分頁 Blob 的詳細資訊,請參閱了解區塊和分頁 Blob

SQL Server 元件

URL:URL 會指定唯一備份檔案的統一資源識別碼 (URI)。 此 URL 是用來提供 SQL Server 備份檔案的位置和名稱。 在此實作中,唯一有效的 URL 是指向 Windows Azure 儲存體帳戶中之分頁 Blob 的 URL。 此 URL 必須指向實際的 Blob,而非只有容器。 如果 Blob 不存在,就會建立 Blob。 如果指定了現有的 Blob,除非同時指定 “WITH FORMAT” 選項,否則 BACKUP 會失敗。

警告注意事項注意

如果您選擇複製並上傳備份檔案至 Windows Azure Blob 儲存體服務,請使用分頁 Blob 做為儲存體選項。 不支援從區塊 Blob 還原。 從區塊 Blob 類型進行 RESTORE 會失敗並出現錯誤。

下面是範例 URL 值:http[s]://ACCOUNTNAME.Blob.core.windows. net/<CONTAINER>/<FILENAME.bak>。 HTTPS 不是必要項目,但是建議使用。

認證:SQL Server 認證是用來儲存連接到 SQL Server 外部資源所需之驗證資訊的物件。 此處,SQL Server 備份和還原程序會使用認證,向 Windows Azure BLOB 儲存體服務驗證。 認證會儲存儲存體帳戶的名稱以及儲存體帳戶的存取金鑰值。 一旦建立認證之後,您必須在發出 BACKUP/RESTORE 陳述式時,在 WITH CREDENTIAL 選項中指定認證。 如需有關如何檢視、複製或重新產生儲存體帳戶之 access keys 的詳細資訊,請參閱儲存體帳戶的存取金鑰

如需有關如何建立 SQL Server 認證的逐步指示,請參閱本主題稍後的<建立認證>範例。

如需有關認證的一般資訊,請參閱認證

如需有關使用認證之其他範例的詳細資訊,請參閱建立 SQL Server Agent Proxy

限制

  • 支援的備份大小上限為 1 TB。

  • 在此實作中,您可以使用 TSQL 或 SMO 來發出 Backup 或 Restore 陳述式。 目前不支援使用 SQL Server Management Studio 備份或還原精靈來備份至 Windows Azure Blob 儲存體服務或從中還原。

  • 不支援建立邏輯裝置名稱。 因此,不支援使用 sp_dumpdevice 或透過 SQL Server Management Studio 加入 URL 做為備份裝置。

  • 不支援附加至現有的備份 Blob。 現有 Blob 的備份只能使用 WITH FORMAT 選項來覆寫。

  • 不支援在單一備份作業中,備份至多個 Blob。 例如,下列程式碼會傳回錯誤:

    BACKUP DATABASE AdventureWorks2012 
    TO URL = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012_1.bak' 
       URL = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012_2.bak' 
          WITH CREDENTIAL = 'mycredential' 
         ,STATS = 5;
    GO 
    
  • 不支援使用 BACKUP 來指定區塊大小。

  • 不支援指定 MAXTRANSFERSIZE。

  • 不支援指定備份組選項 - RETAINDAYS 和 EXPIREDATE。

  • SQL Server 的備份裝置名稱大小上限為 259 個字元。 BACKUP TO URL 會針對用來指定 URL 的必要元素佔用 36 個字元 - ‘https://.blob.core.windows. net//.bak’,而保留 223 個字元供帳戶、容器和 Blob 名稱共用。

支援 Backup/Restore 陳述式

Backup/Restore 陳述式

支援

例外狀況

註解

BACKUP

不支援 BLOCKSIZE 和 MAXTRANSFERSIZE。

需要指定 WITH CREDENTIAL

RESTORE

需要指定 WITH CREDENTIAL

RESTORE FILELISTONLY

需要指定 WITH CREDENTIAL

RESTORE HEADERONLY

需要指定 WITH CREDENTIAL

RESTORE LABELONLY

需要指定 WITH CREDENTIAL

RESTORE VERIFYONLY

需要指定 WITH CREDENTIAL

RESTORE REWINDONLY

如需有關 Backup 陳述式的語法和一般資訊,請參閱<BACKUP (Transact-SQL)>。

如需有關 Restore 陳述式的語法和一般資訊,請參閱<RESTORE (Transact-SQL)>。

支援 Backup 引數

引數

支援

例外狀況

註解

DATABASE

LOG

TO (URL)

與 DISK 和 TAPE 不同,URL 不支援指定或建立邏輯名稱。

這個引數是用來指定備份檔案的 URL 路徑。

MIRROR TO

WITH 選項:

CREDENTIAL

當您使用 BACKUP TO URL 選項來備份至 Windows Azure Blob 儲存體服務時,僅支援 WITH CREDENTIAL。

DIFFERENTIAL

COPY_ONLY

COMPRESSION|NO_COMPRESSION

DESCRIPTION

NAME

EXPIREDATE | RETAINDAYS

NOINIT | INIT

如果使用這個選項,則會被忽略。

您無法附加至 Blob。 若要覆寫備份,請使用 FORMAT 引數。

NOSKIP | SKIP

NOFORMAT | FORMAT

如果使用這個選項,則會被忽略。

除非指定了 WITH FORMAT,否則帶入現有 Blob 的備份會失敗。 指定 WITH FORMAT 時,系統會覆寫現有的 Blob。

MEDIADESCRIPTION

MEDIANAME

BLOCKSIZE

BUFFERCOUNT

MAXTRANSFERSIZE

NO_CHECKSUM | CHECKSUM

STOP_ON_ERROR | CONTINUE_AFTER_ERROR

STATS

REWIND | NOREWIND

UNLOAD | NOUNLOAD

NORECOVERY | STANDBY

NO_TRUNCATE

如需有關 Backup 引數的詳細資訊,請參閱<BACKUP (Transact-SQL)>。

支援 Restore 引數

引數

支援

例外狀況

註解

DATABASE

LOG

FROM (URL)

FROM URL 引數是用來指定備份檔案的 URL 路徑。

WITH 選項:

CREDENTIAL

當您使用 RESTORE FROM URL 選項,從 Windows Azure Blob 儲存體服務還原時,僅支援 WITH CREDENTIAL。

PARTIAL

RECOVERY | NORECOVERY | STANDBY

LOADHISTORY

MOVE

REPLACE

RESTART

RESTRICTED_USER

FILE

PASSWORD

MEDIANAME

MEDIAPASSWORD

BLOCKSIZE

BUFFERCOUNT

MAXTRANSFERSIZE

CHECKSUM | NO_CHECKSUM

STOP_ON_ERROR | CONTINUE_AFTER_ERROR

FILESTREAM

STATS

REWIND | NOREWIND

UNLOAD | NOUNLOAD

KEEP_REPLICATION

KEEP_CDC

ENABLE_BROKER | ERROR_BROKER_CONVERSATIONS | NEW_BROKER

STOPAT | STOPATMARK | STOPBEFOREMARK

如需有關 Restore 引數的詳細資訊,請參閱<RESTORE 引數 (Transact-SQL)>。

範例

本節包含下列範例。

  • 建立認證

  • 備份完整資料庫

  • 備份資料庫和記錄

  • 建立主要檔案群組的完整檔案備份

  • 建立主要檔案群組的差異檔案備份

  • 還原資料庫和移動檔案

  • 使用 STOPAT 還原至時間點

建立認證

下列範例會建立儲存 Windows Azure 儲存體驗證資訊的認證。

  1. Tsql

    IF NOT EXISTS
    (SELECT * FROM sys.credentials 
    WHERE credential_identity = 'mycredential')
    CREATE CREDENTIAL mycredential WITH IDENTITY = 'mystorageaccount'
    ,SECRET = '<storage access key>' ;
    
  2. C#

    // Connect to default sql server instance on local machine
    Server server = new Server(".");
    string identity = "mystorageaccount";
    string secret = "<storage access key>";
    
    // Create a Credential
    string credentialName = "mycredential";
    Credential credential = new Credential(server, credentialName);
    credential.Create(identity, secret);
    
  3. PowerShell

    # create variables
    $storageAccount = "mystorageaccount"
    $storageKey = "<storage access key>"
    $secureString = convertto-securestring $storageKey  -asplaintext -force
    $credentialName = "mycredential"
    
    $srvPath = "SQLSERVER:\SQL\COMPUTERNAME\INSTANCENAME"
    # for default instance, the $srvpath variable would be \"SQLSERVER:\SQL\COMPUTERNAME\DEFAULT\"
    
    # Create a credential
     New-SqlCredential -Name $credentialName -Path $srvpath -Identity $storageAccount -Secret $secureString
    

備份完整資料庫

下列範例會將 AdventureWorks2012 資料庫備份至 Windows Azure Blob 儲存體服務。

  1. Tsql

    BACKUP DATABASE AdventureWorks2012 
    TO URL = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012.bak' 
          WITH CREDENTIAL = 'mycredential' 
         ,COMPRESSION
         ,STATS = 5;
    GO 
    
  1. C#

    // Connect to default sql server instance on local machine
    Server server = new Server(".");
    string identity = "mystorageaccount";
    
    string credentialName = "mycredential";
    string dbName = "AdventureWorks2012";
    string blobContainerName = "mycontainer";
    
    // Generate Unique Url
    string url = String.Format(@"https://{0}.blob.core.windows.net/{1}/{2}-{3}.bak",
            identity,
            blobContainerName,
            dbName,
            DateTime.Now.ToString("s").Replace(":", "-"));
    
    // Backup to Url
    Backup backup = new Backup();
    backup.CredentialName = credentialName;
    backup.Database = dbName;
    backup.CompressionOption = BackupCompressionOptions.On;
    backup.Devices.AddDevice(url, DeviceType.Url);
    backup.SqlBackup(server);
    
  2. PowerShell

    # create variables
    $backupUrlContainer = "https://mystorageaccount.blob.core.windows.net/mycontainer/"
    $credentialName = "mycredential"
    $srvPath = "SQLSERVER:\SQL\COMPUTERNAME\INSTANCENAME" 
    # for default instance, the $srvpath varilable would be \"SQLSERVER:\SQL\COMPUTERNAME\DEFAULT\"
    
    # navigate to SQL Server Instance
    CD $srvPath 
    $backupFile = $backupUrlContainer + "AdventureWorks2012" +  ".bak"
    Backup-SqlDatabase -Database AdventureWorks2012 -backupFile $backupFile  -SqlCredential $credentialName -CompressionOption On   
    

備份資料庫和記錄

下列範例會備份 AdventureWorks2012 範例資料庫,依預設採用簡單復原模式。 為了支援記錄備份,AdventureWorks2012 資料庫會修改成使用完整復原模式。 此範例接著會建立 Windows Azure Blob 的完整資料庫備份,並且在更新活動一段時間之後,備份記錄。 這個範例會建立含有日期時間戳記的備份檔案名稱。

  1. Tsql

    -- To permit log backups, before the full database backup, modify the database 
    -- to use the full recovery model.
    USE master;
    GO
    ALTER DATABASE AdventureWorks2012
       SET RECOVERY FULL;
    GO
    
    
    -- Back up the full AdventureWorks2012 database.
           -- First create a file name for the backup file with DateTime stamp
    
    DECLARE @Full_Filename AS VARCHAR (300);
    SET @Full_Filename = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012_Full_'+ 
    REPLACE (REPLACE (REPLACE (CONVERT (VARCHAR (40), GETDATE (), 120), '-','_'),':', '_'),' ', '_') + '.bak'; 
    --Back up Adventureworks2012 database
    
    BACKUP DATABASE AdventureWorks2012
    TO URL =  @Full_Filename
    WITH CREDENTIAL = 'mycredential';
    ,COMPRESSION
    GO
    -- Back up the AdventureWorks2012 log.
    DECLARE @Log_Filename AS VARCHAR (300);
    SET @Log_Filename = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012_Log_'+ 
    REPLACE (REPLACE (REPLACE (CONVERT (VARCHAR (40), GETDATE (), 120), '-','_'),':', '_'),' ', '_') + '.trn';
    BACKUP LOG AdventureWorks2012
     TO URL = @Log_Filename
    WITH CREDENTIAL = 'mycredential'
    ,COMPRESSION;
    GO
    
  2. C#

    // Connect to default sql server instance on local machine
    Server server = new Server(".");
    string identity = "mystorageaccount";
    
    string credentialName = "mycredential";
    string dbName = "AdventureWorks2012";
    string blobContainerName = "mycontainer";
    
    
    // Generate Unique Url for data backup
    string urlDataBackup = String.Format(@"https://{0}.blob.core.windows.net/{1}/{2}_Data-{3}.bak",
            identity,
            blobContainerName,
            dbName,
            DateTime.Now.ToString("s").Replace(":", "-"));
    
    // Backup Database to Url
    Backup backupData = new Backup();
    backupData.CredentialName = credentialName;
    backupData.Database = dbName;
    backup.CompressionOption = BackupCompressionOptions.On;
    backupData.Devices.AddDevice(urlDataBackup, DeviceType.Url);
    backupData.SqlBackup(server);
    
    // Generate Unique Url for data backup
    string urlLogBackup = String.Format(@"https://{0}.blob.core.windows.net/{1}/{2}_Log-{3}.bak",
            identity,
            blobContainerName,
            dbName,
            DateTime.Now.ToString("s").Replace(":", "-"));
    
    // Backup Database Log to Url
    Backup backupLog = new Backup();
    backupLog.CredentialName = credentialName;
    backupLog.Database = dbName;
    backup.CompressionOption = BackupCompressionOptions.On;
    backupLog.Devices.AddDevice(urlLogBackup, DeviceType.Url);
    backupLog.Action = BackupActionType.Log;
    backupLog.SqlBackup(server);
    
  3. PowerShell

    #create variables
    $backupUrlContainer = "https://mystorageaccount.blob.core.windows.net/mycontainer/"
    $credentialName = "mycredential"
    $srvPath = "SQLSERVER:\SQL\COMPUTERNAME\INSTANCENAME"
    # for default instance, the $srvpath variable would be \"SQLSERVER:\SQL\COMPUTERNAME\DEFAULT\"
    
    # navigate to theSQL Server Instance
    
    CD $srvPath 
    #Create a unique file name for the full database backup
    $backupFile = $backupUrlContainer + "AdventureWorks2012_" + (Get-Date).ToString("s").Replace("-","_").Replace(":", "_").Replace(" ","_").Replace("/", "_") +  ".bak"
    
    #Backup Database to URL
    
    Backup-SqlDatabase -Database AdventureWorks2012 -backupFile $backupFile  -SqlCredential $credentialName -CompressionOption On -BackupAction Database  
    
    #Create a unique file name for log backup
    
    $backupFile = $backupUrlContainer + "AdventureWorks2012_" + (Get-Date).ToString("s").Replace("-","_").Replace(":", "_").Replace(" ","_").Replace("/", "_") +  ".trn"
    
    #Backup Log to URL
    
    Backup-SqlDatabase -Database AdventureWorks2012 -backupFile $backupFile  -SqlCredential $credentialName -CompressionOption On -BackupAction Log  
    

建立主要檔案群組的完整檔案備份

下列範例會建立主要檔案群組的完整檔案備份。

  1. Tsql

    --Back up the files in Primary:
    BACKUP DATABASE AdventureWorks2012
       FILEGROUP = 'Primary'
       TO URL = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012files.bck'
       WITH CREDENTIAL = 'mycredential'
       ,COMPRESSION;
    GO
    
  2. C#

    // Connect to default sql server instance on local machine
    Server server = new Server(".");
    string identity = "mystorageaccount";
    
    string credentialName = "mycredential";
    string dbName = "AdventureWorks2012";
    string blobContainerName = "mycontainer";
    
    // Generate Unique Url
    string url = String.Format(@"https://{0}.blob.core.windows.net/{1}/{2}-{3}.bck",
            identity,
            blobContainerName,
            dbName,
            DateTime.Now.ToString("s").Replace(":", "-"));
    
    // Backup to Url
    Backup backup = new Backup();
    backup.CredentialName = credentialName;
    backup.Database = dbName;
    backup.Action = BackupActionType.Files;
    backup.DatabaseFileGroups.Add("PRIMARY");
    backup.CompressionOption = BackupCompressionOptions.On;
    backup.Devices.AddDevice(url, DeviceType.Url);
    backup.SqlBackup(server);
    
  3. PowerShell

    #create variables
    $backupUrlContainer = "https://mystorageaccount.blob.core.windows.net/mycontainer/"
    $credentialName = "mycredential"
    $srvPath = "SQLSERVER:\SQL\COMPUTERNAME\INSTANCENAME"
    # for default instance, the $srvpath variable would be \"SQLSERVER:\SQL\COMPUTERNAME\DEFAULT\"
    
    # navigate to the SQL Server Instance
    
    CD $srvPath 
    #Create a unique file name for the file backup
    $backupFile = $backupUrlContainer + "AdventureWorks2012_" + (Get-Date).ToString("s").Replace("-","_").Replace(":", "_").Replace(" ","_").Replace("/", "_") +  ".bck"
    
    #Backup Primary File Group to URL
    
    Backup-SqlDatabase -Database AdventureWorks2012 -backupFile $backupFile  -SqlCredential $credentialName -CompressionOption On -BackupAction Files -DatabaseFileGroup Primary  
    

建立主要檔案群組的差異檔案備份

下列範例會建立主要檔案群組的差異檔案備份。

  1. Tsql

    --Back up the files in Primary:
    BACKUP DATABASE AdventureWorks2012
       FILEGROUP = 'Primary'
       TO URL = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012filesdiff.bck'
       WITH 
          CREDENTIAL = 'mycredential'
          ,COMPRESSION
      ,DIFFERENTIAL;
    GO
    
  2. C#

    // Connect to default sql server instance on local machine
    Server server = new Server(".");
    string identity = "mystorageaccount";
    
    string credentialName = "mycredential";
    string dbName = "AdventureWorks2012";
    string blobContainerName = "mycontainer";
    
    
    // Generate Unique Url
    string url = String.Format(@"https://{0}.blob.core.windows.net/{1}/{2}-{3}.bak",
            identity,
            blobContainerName,
            dbName,
            DateTime.Now.ToString("s").Replace(":", "-"));
    
    
    // Backup to Url
    Backup backup = new Backup();
    backup.CredentialName = credentialName;
    backup.Database = dbName;
    backup.Action = BackupActionType.Files;
    backup.DatabaseFileGroups.Add("PRIMARY");
    backup.Incremental = true;
    backup.CompressionOption = BackupCompressionOptions.On;
    backup.Devices.AddDevice(url, DeviceType.Url);
    backup.SqlBackup(server);
    
  3. PowerShell

    #create variables
    $backupUrlContainer = "https://mystorageaccount.blob.core.windows.net/mycontainer/"
    $credentialName = "mycredential"
    $srvPath = "SQLSERVER:\SQL\COMUTERNAME\INSTANCENAME"
    # for default instance, the $srvpath variable would be \"SQLSERVER:\SQL\COMPUTERNAME\DEFAULT\"
    
    # navigate to SQL Server Instance
    
    CD $srvPath 
    
    #create a unique file name for the full backup
    $backupdbFile = $backupUrlContainer + "AdventureWorks2012_" + (Get-Date).ToString("s").Replace("-","_").Replace(":", "_").Replace(" ","_").Replace("/", "_") +  ".bak"
    
    #Create a differential backup of the primary filegroup
    
    Backup-SqlDatabase -Database AdventureWorks2012 -backupFile $backupFile  -SqlCredential $credentialName -CompressionOption On -BackupAction Files -DatabaseFileGroup Primary -Incremental  
    

還原資料庫和移動檔案

若要還原完整資料庫備份並將還原的資料庫移至 C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data 目錄,請使用下列步驟。

  1. Tsql

    -- Backup the tail of the log first
    
    DECLARE @Log_Filename AS VARCHAR (300);
    SET @Log_Filename = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012_Log_'+ 
    REPLACE (REPLACE (REPLACE (CONVERT (VARCHAR (40), GETDATE (), 120), '-','_'),':', '_'),' ', '_') + '.trn';
    BACKUP LOG AdventureWorks2012
     TO URL = @Log_Filename
    WITH CREDENTIAL = 'mycredential'
    ,NORECOVERY;
    GO
    
    RESTORE DATABASE AdventureWorks2012 FROM URL = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012.bak'
    WITH CREDENTIAL = 'mycredential'
    ,MOVE 'AdventureWorks2012_data' to 'C:\Program Files\Microsoft SQL Server\myinstance\MSSQL\DATA\AdventureWorks2012.mdf'
    ,MOVE 'AdventureWorks2012_log' to 'C:\Program Files\Microsoft SQL Server\myinstance\MSSQL\DATA\AdventureWorks2012.ldf'
          ,STATS = 5 
    
  2. C#

    // Connect to default sql server instance on local machine
    Server server = new Server(".");
    string identity = "mystorageaccount";
    
    string credentialName = "mycredential";
    string dbName = "AdventureWorks2012";
    string blobContainerName = "mycontainer";
    
    // Generate Unique Url
    string urlBackupData = String.Format(@"https://{0}.blob.core.windows.net/{1}/{2}-Data{3}.bak",
            identity,
            blobContainerName,
            dbName,
            DateTime.Now.ToString("s").Replace(":", "-"));
    
    
    // Backup to Url
    Backup backup = new Backup();
    backup.CredentialName = credentialName;
    backup.Database = dbName;
    backup.Devices.AddDevice(urlBackupData, DeviceType.Url);
    backup.SqlBackup(server);
    
    // Generate Unique Url for tail log backup
    string urlTailLogBackup = String.Format(@"https://{0}.blob.core.windows.net/{1}/{2}-TailLog{3}.bak",
            identity,
            blobContainerName,
            dbName,
            DateTime.Now.ToString("s").Replace(":", "-"));
    
    
    // Backup Tail Log to Url
    Backup backupTailLog = new Backup();
    backupTailLog.CredentialName = credentialName;
    backupTailLog.Database = dbName;
    backupTailLog.Action = BackupActionType.Log;
    backupTailLog.NoRecovery = true;
    backupTailLog.Devices.AddDevice(urlTailLogBackup, DeviceType.Url);
    backupTailLog.SqlBackup(server);
    
    // Restore a database and move files
    string newDataFilePath = server.MasterDBLogPath  + @"\" + dbName + DateTime.Now.ToString("s").Replace(":", "-") + ".mdf";
    string newLogFilePath = server.MasterDBLogPath  + @"\" + dbName + DateTime.Now.ToString("s").Replace(":", "-") + ".ldf";
    
    Restore restore = new Restore();
    restore.CredentialName = credentialName;
    restore.Database = dbName;
    restore.ReplaceDatabase = true;
    restore.Devices.AddDevice(urlBackupData, DeviceType.Url);
    restore.RelocateFiles.Add(new RelocateFile(dbName, newDataFilePath));
    restore.RelocateFiles.Add(new RelocateFile(dbName+ "_Log", newLogFilePath));
    restore.SqlRestore(server); 
    
  3. PowerShell

    #create variables
    $backupUrlContainer = "https://mystorageaccount.blob.core.windows.net/mycontainer/"
    $credentialName = "mycredential"
    $srvPath = "SQLSERVER:\SQL\COMPUTERNAME\INSTNACENAME"
    # for default instance, the $srvpath variable would be \"SQLSERVER:\SQL\COMPUTERNAME\DEFAULT\"
    
    # navigate to SQL Server Instance 
    
    CD $srvPath 
    
    #create a unique file name for the full backup
    $backupdbFile = $backupUrlContainer + "AdventureWorks2012_" + (Get-Date).ToString("s").Replace("-","_").Replace(":", "_").Replace(" ","_").Replace("/", "_") +  ".bak"
    
    # Full database backup to URL
    Backup-SqlDatabase -Database AdventureWorks2012 -backupFile $backupdbFile  -SqlCredential $credentialName -CompressionOption On    
    
    #Create a unique file name for the tail log backup
    $backuplogFile = $backupUrlContainer + "AdventureWorks2012_" + (Get-Date).ToString("s").Replace("-","_").Replace(":", "_").Replace(" ","_").Replace("/", "_") +  ".trn"
    
    #Backup tail log to URL
    
    Backup-SqlDatabase -Database AdventureWorks2012 -backupFile $backupFile  -SqlCredential $credentialName  -BackupAction Log -NoRecovery  
    
    # Restore Database and move files
    
    $newDataFilePath = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile ("AdventureWorks_Data","C:\Program Files\Microsoft SQL Server\myinstance\MSSQL\DATA\AdventureWorks2012.mdf")
    $newLogFilePath = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("AdventureWorks_Log","C:\Program Files\Microsoft SQL Server\myinstance\MSSQL\DATA\AdventureWorks2012.ldf")
    
    Restore-SqlDatabase -Database AdventureWorks2012 -SqlCredential $credentialName -BackupFile $backupdbFile -RelocateFile @($newDataFilePath,$newLogFilePath)  
    

使用 STOPAT 還原至時間點

下列範例會將資料庫還原至某個時間點的狀態,並且顯示還原作業。

  1. Tsql

    RESTORE DATABASE AdventureWorks FROM URL = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012.bak' 
    WITH 
     CREDENTIAL = 'mycredential'
    ,MOVE 'AdventureWorks2012_data' to 'C:\Program Files\Microsoft SQL Server\myinstance\MSSQL\DATA\AdventureWorks2012.mdf'
    ,Move 'AdventureWorks2012_log' to 'C:\Program Files\Microsoft SQL Server\myinstance\MSSQL\DATA\AdventureWorks2012.ldf'
    ,NORECOVERY
    --,REPLACE
    ,STATS = 5;
    GO 
    
    RESTORE LOG AdventureWorks FROM URL = 'https://mystorageaccount.blob.core.windows.net/mycontainer/AdventureWorks2012.trn' 
    WITH CREDENTIAL = 'mycredential'
    ,RECOVERY 
    ,STOPAT = 'Oct 23, 2012 5:00 PM' 
    GO
    
  2. C#

    // Connect to default sql server instance on local machine
    Server server = new Server(".");
    string identity = "mystorageaccount";
    
    string credentialName = "mycredential";
    string dbName = "AdventureWorks2012";
    string blobContainerName = "mycontainer";
    
    // Generate Unique Url
    string urlBackupData = String.Format(@"https://{0}.blob.core.windows.net/{1}/{2}-Data{3}.bak",
            identity,
            blobContainerName,
            dbName,
            DateTime.Now.ToString("s").Replace(":", "-"));
    
    
    // Backup to Url
    Backup backup = new Backup();
    backup.CredentialName = credentialName;
    backup.Database = dbName;
    backup.Devices.AddDevice(urlBackupData, DeviceType.Url);
    backup.SqlBackup(server);
    
    // Generate Unique Url for Tail Log backup
    string urlTailLogBackup = String.Format(@"https://{0}.blob.core.windows.net/{1}/{2}-TailLog{3}.bak",
            identity,
            blobContainerName,
            dbName,
            DateTime.Now.ToString("s").Replace(":", "-"));
    
    
    // Backup Tail Log to Url
    Backup backupTailLog = new Backup();
    backupTailLog.CredentialName = credentialName;
    backupTailLog.Database = dbName;
    backupTailLog.Action = BackupActionType.Log;
    backupTailLog.NoRecovery = true;
    backupTailLog.Devices.AddDevice(urlTailLogBackup, DeviceType.Url);
    backupTailLog.SqlBackup(server);
    
    // Restore a database and move files
    string newDataFilePath = server.MasterDBLogPath + @"\" + dbName + DateTime.Now.ToString("s").Replace(":", "-") + ".mdf";
    string newLogFilePath = server.MasterDBLogPath + @"\" + dbName + DateTime.Now.ToString("s").Replace(":", "-") + ".ldf";
    
    Restore restore = new Restore();
    restore.CredentialName = credentialName;
    restore.Database = dbName;
    restore.ReplaceDatabase = true;
    restore.NoRecovery = true;
    restore.Devices.AddDevice(urlBackupData, DeviceType.Url);
    restore.RelocateFiles.Add(new RelocateFile(dbName, newDataFilePath));
    restore.RelocateFiles.Add(new RelocateFile(dbName + "_Log", newLogFilePath));
    restore.SqlRestore(server);
    
    // Restore transaction Log with stop at 
    Restore restoreLog = new Restore();
    restoreLog.CredentialName = credentialName;
    restoreLog.Database = dbName;
    restoreLog.Action = RestoreActionType.Log;
    restoreLog.Devices.AddDevice(urlBackupData, DeviceType.Url);
    restoreLog.ToPointInTime = DateTime.Now.ToString(); 
    restoreLog.SqlRestore(server);
    
  3. PowerShell

    #create variables
    $backupUrlContainer = "https://mystorageaccount.blob.core.windows.net/mycontainer/"
    $credentialName = "mycredential"
    $srvPath = "SQLSERVER:\SQL\COMPUTERNAME\INSTANCENAME"
    # for default instance, the $srvpath variable would be \"SQLSERVER:\SQL\COMPUTERNAME\DEFAULT\"
    
    # Navigate to SQL Server Instance Directory
    
    CD $srvPath 
    
    #create a unique file name for the full backup
    $backupdbFile = $backupUrlContainer + "AdventureWorks2012_" + (Get-Date).ToString("s").Replace("-","_").Replace(":", "_").Replace(" ","_").Replace("/", "_") +  ".bak"
    
    # Full database backup to URL
    Backup-SqlDatabase -Database AdventureWorks2012 -backupFile $backupdbFile  -SqlCredential $credentialName -CompressionOption On   
    
    #Create a unique file name for the tail log backup
    $backuplogFile = $backupUrlContainer + "AdventureWorks2012_" + (Get-Date).ToString("s").Replace("-","_").Replace(":", "_").Replace(" ","_").Replace("/", "_") +  ".trn"
    
    #Backup tail log to URL
    
    Backup-SqlDatabase -Database AdventureWorks2012 -backupFile $backupFile  -SqlCredential $credentialName  -BackupAction Log -NoRecovery   
    
    # Restore Database and move files
    
    $newDataFilePath = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile ("AdventureWorks_Data","C:\Program Files\Microsoft SQL Server\myinstance\MSSQL\DATA\AdventureWorks2012.mdf")
    $newLogFilePath = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("AdventureWorks_Log","C:\Program Files\Microsoft SQL Server\myinstance\MSSQL\DATA\AdventureWorks2012.ldf")
    
    Restore-SqlDatabase -Database AdventureWorks2012 -SqlCredential $credentialName -BackupFile $backupdbFile -RelocateFile @($newDataFilePath,$newLogFilePath) -NoRecovery  
    
    # Restore Transaction log with Stop At:
    Restore-SqlDatabase -Database AdventureWorks2012 -SqlCredential $credentialName -BackupFile $backuplogFile  -ToPointInTime (Get-Date).ToString()