Share via


使用 Azure CLI 將 Azure SQL Database 中的資料庫複製到新伺服器

適用於:Azure SQL Database

此 Azure CLI 指令碼範例會在新的伺服器中建立現有資料庫的複本。

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

必要條件

範例指令碼

啟動 Azure Cloud Shell

Azure Cloud Shell 是免費的互動式 Shell,可讓您用來執行本文中的步驟。 它具有預先安裝和設定的共用 Azure 工具,可與您的帳戶搭配使用。

若要開啟 Cloud Shell,請選取程式碼區塊右上角的 [試試看]。 您也可以移至 https://shell.azure.com ,從另一個瀏覽器索引標籤啟動 Cloud Shell。

當開啟 Cloud Shell 時,請確認已為您的環境選取 Bash。 後續的工作階段將會在 Bash 環境中使用 Azure CLI。 選取 [複製] 即可複製程式碼區塊,將它貼到 Cloud Shell 中,然後按 Enter 鍵加以執行。

登入 Azure

系統會在登入的初始帳戶下自動驗證 Cloud Shell。 使用下列指令碼透過不同的訂閱登入,並將 <Subscription ID> 取代為您的 Azure 訂用帳戶識別碼。 如果您沒有 Azure 訂用帳戶,請在開始之前先建立 Azure 免費帳戶

subscription="<subscriptionId>" # add subscription here

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

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

執行指令碼

# Copy a database in Azure SQL Database to a new server

# Variable block
let "randomIdentifier=$RANDOM*$RANDOM"
location="East US"
resourceGroup="msdocs-azuresql-rg-$randomIdentifier"
tag="copy-database-to-new-server"
server="msdocs-azuresql-server-$randomIdentifier"
database="msdocsazuresqldb$randomIdentifier"
login="azureuser"
password="Pa$$w0rD-$randomIdentifier"
targetResourceGroup="msdocs-azuresql-targetrg-$randomIdentifier"
targetLocation="Central US"
targetServer="msdocs-azuresql-targetServer-$randomIdentifier"
targetDatabase="msdocs-azuresql-targetDatabase-$randomIdentifier"

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

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

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

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

echo "Copying $database on $server to $targetDatabase on $targetServer..."
az sql db copy --dest-name $targetDatabase --dest-resource-group $targetResourceGroup --dest-server $targetServer --name $database --resource-group $resourceGroup --server $server

清除資源

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

az group delete --name $targetResourceGroup
az group delete --name $resourceGroup

範例參考

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

Command 描述
az sql db copy 為使用目前快照集的資料庫建立複本。

後續步驟

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

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