首页 > 解决方案 > 无法使用 PowerShell 或 T-SQL 将 SQL 数据库备份到 Azure Blob 存储

问题描述

我相信我正在关注 Microsoft 将 SQL 数据库备份到 Azure Blob 存储的文档;但是,无论我尝试什么,我都会遇到同样的错误。

例如,以下代码创建 SQL 凭据并尝试备份数据库。

运行它时,错误表明我不能使用 WITH CREDENTIAL 和 SAS,但微软在他们的文档中演示了直接使用这两者https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/ sql-server-backup-to-url?view=sql-server-2017#Examples)!

declare @databaseName varchar(50)
declare @destinationAzureStorageContainerPath varchar(256)
declare @destinationBlobPath varchar(256)
declare @timestampUtc as nvarchar(30)

select @timestampUtc = replace(convert(nvarchar(30), getutcdate(), 126), ':', '_');
set @databaseName = 'DWConfiguration'
set @destinationAzureStorageContainerPath = 'https://mystorageaccount.blob.core.windows.net/mystoragecontainer/'
SET @destinationBlobPath = @destinationAzureStorageContainerPath + @databaseName + '_' + @timestampUtc + '.BAK'

if not exists
(select * from sys.credentials   
where name = 'https://mystorageaccount.blob.core.windows.net/mystoragecontainer/')  
create CREDENTIAL [https://mystorageaccount.blob.core.windows.net/mystoragecontainer/] 
  with IDENTITY = 'SHARED ACCESS SIGNATURE',
  SECRET = 'sv... this is my token ...';

backup DATABASE @databaseName   
to URL = @destinationBlobPath
with CREDENTIAL = 'https://mystorageaccount.blob.core.windows.net/mystoragecontainer/'
,COMPRESSION  
,STATS = 5

错误:

消息 3225,级别 16,状态 1,第 28 行 WITH CREDENTIAL 语法的使用对于包含共享访问签名的凭据无效。消息 3013,级别 16,状态 1,第 28 行备份数据库异常终止。

作为替代方法,我决定使用 PowerShell。

Backup-SqlDatabase -ServerInstance "myserver" -Database "DWConfiguration" -BackupFile "https://mystorageaccount.blob.core.windows.net/mystoragecontainer/mydatabase_2019-01-04T20_01_03.127.bak" -SqlCredential "https://mystorageaccount.blob.core.windows.net/mystoragecontainer/"

如您所见,它会导致同样烦人的错误!

Backup-SqlDatabase:System.Data.SqlClient.SqlError:使用 WITH CREDENTIAL 语法对于包含共享访问签名的凭据无效。

在 blob 本身上,我设置了“私有(无匿名访问)”。我只希望经过身份验证的请求能够访问 blob。这可能是问题吗?如果是这样,为什么不WITH CREDENTIAL解决这个问题?

在此处输入图像描述

如何简单地将我的 SQL 数据库备份保存到我的 Azure 存储帐户?

参考。https://blog.sqlauthority.com/2018/07/17/sql-server-backup-to-url-script-to-generate-credential-and-backup-using-shared-access-signature-sas/

标签: sql-serverazurepowershellazure-blob-storagedatabase-backups

解决方案


我认为你在你的 sql 脚本中犯了一个错误。

您创建了凭据“使用共享访问签名”,但是在备份时您使用了“使用存储帐户身份和访问密钥的 URL”,这与您之前创建的 sas 不匹配。

我在我身边对其进行了测试,并且工作正常(创建凭据“使用共享访问签名”,并使用“使用共享访问签名的 URL”进行备份)。

IF NOT EXISTS (SELECT * FROM sys.credentials   
               WHERE name = 'https://xxx.blob.core.windows.net/container')  
CREATE CREDENTIAL [https://xxx.blob.core.windows.net/container] 
  WITH IDENTITY = 'SHARED ACCESS SIGNATURE',  
  SECRET = 'sv=xxx';


BACKUP DATABASE MyTest   
TO URL = 'https://xxx.blob.core.windows.net/container/123.bak'  
GO

测试结果如下:

在此处输入图像描述


推荐阅读