You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Set-AzSqlDatabase重命名Azure SQL数据库的疑似缓存问题

Azure SQL 数据库重命名缓存问题解决方案

问题背景

我们的Azure SQL Server包含多组数据库,每组由一个“master”数据库和一个“current”数据库组成,每日自动化流程执行以下步骤:

  • 使用New-AzSqlDatabaseCopy复制“master”数据库到临时名称
  • 使用Remove-AzSqlDatabase删除“current”数据库
  • 使用Set-AzSqlDatabase -NewName将临时数据库重命名为“current”

流程稳定运行一年后,近期Set-AzSqlDatabase频繁报错:

Resource with identifier '/subscriptions/<subscriptionid>/resourceGroups/<resourcegroup>/providers/Microsoft.Sql/servers/<servername>/databases/DBCurrent' already exists.

但通过SSMS或Get-AzSqlDatabase均无法查询到该数据库。已尝试重试机制、改用Azure CLI的az sql db rename,仍出现相同错误;仅直接调用Azure REST API执行重命名可每次成功。使用Az.Sql模块版本4.14.0,调用Clear-AzConfig无效,推测为PowerShell/CLI的本地缓存问题。

缓存清除及解决方案

1. 清除Az PowerShell本地缓存

Az PowerShell会在本地存储资源上下文和缓存数据,可通过以下步骤清除:

  • 关闭所有PowerShell会话
  • 删除本地缓存目录:%USERPROFILE%\.Azure\Cache(Windows)或~/.Azure/Cache(Linux/macOS)下的所有文件
  • 重新打开PowerShell并重新登录Azure:Connect-AzAccount

2. 禁用Az上下文自动保存并强制刷新

在自动化脚本中添加以下命令,避免缓存残留:

# 禁用上下文自动保存
Update-AzConfig -DisableAzContextAutoSave $true

# 断开并重新连接账户
Disconnect-AzAccount -Force
Connect-AzAccount -Subscription "<subscriptionid>"

3. 直接调用Azure REST API替代(已验证有效)

既然REST API无缓存问题,可在PowerShell中直接调用替代Set-AzSqlDatabase:

# 获取Azure访问令牌
$context = Get-AzContext
$authToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate(
    $context.Account,
    $context.Environment,
    $context.Tenant.Id,
    $null,
    [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never,
    $null,
    "https://management.azure.com"
).AccessToken

# 配置参数
$subscriptionId = "<subscriptionid>"
$resourceGroup = "<resourcegroup>"
$serverName = "<servername>"
$tempDbName = "<临时数据库名称>"
$targetDbName = "DBCurrent"

# 构造REST API请求
$apiUri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Sql/servers/$serverName/databases/$tempDbName?api-version=2021-11-01"
$requestBody = @{
    properties = @{
        newName = $targetDbName
    }
} | ConvertTo-Json

# 执行重命名
Invoke-RestMethod -Uri $apiUri -Method Patch -Headers @{
    "Authorization" = "Bearer $authToken"
    "Content-Type" = "application/json"
} -Body $requestBody

4. Azure CLI缓存清除

若使用Azure CLI执行重命名,可通过以下方式清除缓存:

# 清除账户缓存
az account clear

# 重新登录
az login --subscription "<subscriptionid>"

# 执行重命名时禁用缓存(临时生效)
AZURE_CLI_DISABLE_CONNECTION_CACHE=1 az sql db rename --resource-group <resourcegroup> --server <servername> --name <临时库名> --new-name DBCurrent

内容的提问来源于stack exchange,提问作者bmolsbeck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 07:50:21