Share via


使用 Azure CLI 將 Azure SQL Database 中的單一資料庫還原到較早的時間點

適用於:Azure SQL Database

此 Azure CLI 指令碼範例會將 Azure SQL Database 中的單一資料庫還原至特定時間點。

如果您沒有 Azure 訂用帳戶,請在開始之前先建立 Azure 免費帳戶

必要條件

範例指令碼

針對此指令碼,請在本機使用 Azure CLI,因為在 Cloud Shell 中執行將花費過長時間。

登入 Azure

使用下列指令碼,以使用特定訂閱進行登入。

subscription="<subscriptionId>" # add subscription here

az account set -s $subscription # ...or use 'az login'

如需詳細資訊,請參閱設定使用中訂閱以互動方式登入

執行指令碼

# Restore a single database in Azure SQL Database to an earlier point in time

# Use Bash rather than Cloud Shell due to its timeout at 20 minutes when no interactive activity 
# In Windows, run Bash in a Docker container to sync time zones between Azure and Bash.

# Variable block
let "randomIdentifier=$RANDOM*$RANDOM"
location="East US"
resourceGroup="msdocs-sql-rg-$randomIdentifier"
tag="restore-database"
server="msdocs-azuresql-server-$randomIdentifier"
database="msdocsazuresqldb$randomIdentifier"
restoreServer="restoreServer-$randomIdentifier"
login="azureuser"
password="Pa$$w0rD-$randomIdentifier"

echo "Using resource group $resourceGroup with login: $login, password: $password..."

echo "Creating $resourceGroup in "$location"..."
az group create --name $resourceGroup --location "$location" --tags $tag

echo "Creating $server in $location..."
az sql server create --name $server --resource-group $resourceGroup --location "$location" --admin-user $login --admin-password $password

echo "Creating $database on $server..."
az sql db create --resource-group $resourceGroup --server $server --name $database --service-objective S0

# Sleeping commands to wait long enough for automatic backup to be created
echo "Sleeping..."
sleep 30m

# Restore a server from backup to a new server
# To specify a specific point-in-time (in UTC) to restore from, use the ISO8601 format:
# restorePoint=“2021-07-09T13:10:00Z”
restorePoint=$(date +%s)
restorePoint=$(expr $restorePoint - 60)
restorePoint=$(date -d @$restorePoint +"%Y-%m-%dT%T")
echo $restorePoint

echo "Restoring to $restoreServer"
az sql db restore --dest-name $restoreServer --edition Standard --name $database --resource-group $resourceGroup --server $server --service-objective S0 --time $restorePoint

清除資源

您可以使用下列命令來移除資源群組及所有與其相關聯的資源,除非您仍持續需要這些資源,否則請使用 az group delete 命令。 某些資源可能需要一些時間才能建立或刪除。

az group delete --name $resourceGroup

範例參考

此指令碼會使用下列命令。 下表中的每個命令都會連結至命令特定的文件。

Command 描述
az sql db restore 還原資料庫命令。

後續步驟

如需 Azure CLI 的詳細資訊,請參閱 Azure CLI 文件

其他的 SQL Database CLI 指令碼範例可於 Azure SQL Database 文件中找到。