使用 PowerShell 使用 Azure Data Factory 大量複製多個資料表

適用于: Azure Data Factory Azure Synapse Analytics

提示

試用 Microsoft Fabric 中的 Data Factory,這是適用于企業的單一分析解決方案。 Microsoft Fabric 涵蓋從資料移動到資料科學、即時分析、商業智慧和報告等所有專案。 瞭解如何 免費啟動新的試用版

本教學課程示範 如何將數個數據表從 Azure SQL 資料庫複製到 Azure Synapse Analytics 。 您也可以在其他複製案例中套用相同的模式。 例如,將資料表從 SQL Server/Oracle 複製到 Azure SQL 資料庫/資料倉儲/Azure Blob,將不同的路徑從 Blob 複製到 Azure SQL 資料庫 資料表。

概括而言,本教學課程包含下列步驟:

  • 建立資料處理站。
  • 建立 Azure SQL 資料庫、Azure Synapse Analytics 和Azure 儲存體連結服務。
  • 建立 Azure SQL 資料庫和 Azure Synapse Analytics 資料集。
  • 建立管線來查閱要複製的資料表,並建立另一個管線來執行實際的複製作業。
  • 啟動管線執行。
  • 監視管線和活動執行。

本教學課程使用 Azure PowerShell。 若要瞭解如何使用其他工具/SDK 來建立資料處理站,請參閱 快速入門

端對端工作流程

在此案例中,我們在 Azure SQL 資料庫中有一些資料表想要複製到 Azure Synapse Analytics。 以下是在管線中發生的工作流程中的邏輯步驟順序:

Workflow

  • 第一個管線會查閱需要複製到接收資料存放區的資料表清單。 或者,您可以維護中繼資料資料表,其中列出要複製到接收資料存放區的所有資料表。 然後,管線會觸發另一個管線,它會逐一查看資料庫中的每個資料表,並執行資料複製作業。
  • 第二個管線會執行實際的複本。 它會使用資料表清單做為參數。 針對清單中的每個資料表,將 Azure SQL 資料庫中的特定資料表複製到 Azure Synapse Analytics 中的對應資料表,以透過 Blob 儲存體和 PolyBase 存複製,以獲得最佳效能。 在此範例中,第一個管線會將資料表清單當做 參數的值傳遞。

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

必要條件

注意

建議您使用 Azure Az PowerShell 模組來與 Azure 互動。 請參閱安裝 Azure PowerShell 以開始使用。 若要了解如何移轉至 Az PowerShell 模組,請參閱將 Azure PowerShell 從 AzureRM 移轉至 Az

  • Azure PowerShell。 遵循如何安裝和設定 Azure PowerShell 中的 指示。
  • Azure 儲存體帳戶 。 Azure 儲存體帳戶會作為大量複製作業中的暫存 Blob 儲存體。
  • Azure SQL Database。 此資料庫包含來源資料。
  • Azure Synapse Analytics。 此資料倉儲會保存從SQL 資料庫複製的資料。

準備SQL 資料庫和 Azure Synapse Analytics

準備來源 Azure SQL 資料庫

遵循 在 Azure SQL 資料庫 中建立資料庫一文,在 SQL 資料庫 中建立具有 Adventure Works LT 範例資料的資料庫。 本教學課程會將此範例資料庫的所有資料表複製到 Azure Synapse Analytics。

準備接收 Azure Synapse Analytics

  1. 如果您沒有 Azure Synapse Analytics 工作區,請參閱 開始使用 Azure Synapse Analytics 一文,以取得建立 Azure Synapse Analytics 的步驟。

  2. 在 Azure Synapse Analytics 中建立對應的資料表架構。 您可以使用 Azure Data Factory 在稍後的步驟中移轉/複製資料。

存取 SQL Server 的 Azure 服務

針對 SQL 資料庫 和 Azure Synapse Analytics,允許 Azure 服務存取 SQL Server。 請確定已為您的伺服器開啟 [ 允許存取 Azure 服務 ] 設定。 此設定可讓 Data Factory 服務從 Azure SQL 資料庫讀取資料,並將資料寫入 Azure Synapse Analytics。 若要確認並開啟此設定,請執行下列步驟:

  1. 按一下左側的 [ 所有服務 ],然後按一下 [ SQL 伺服器 ]。
  2. 選取您的伺服器,然後按一下 [設定 ] 下的 [ 防火牆 ]。
  3. 在 [ 防火牆設定 ] 頁面中,按一下 [開啟 ] 以允許 存取 Azure 服務

建立資料處理站

  1. 啟動 PowerShell 。 讓 Azure PowerShell 保持開啟,直到本教學課程結束為止。 如果您關閉並重新開啟,則必須再次執行命令。

    執行下列命令,然後輸入您用來登入Azure 入口網站的使用者名稱和密碼:

    Connect-AzAccount
    

    執行下列命令以檢視此帳戶的所有訂用帳戶:

    Get-AzSubscription
    

    執行下列命令以選取您想要使用的訂用帳戶。 以 Azure 訂用帳戶的識別碼取代 SubscriptionId

    Select-AzSubscription -SubscriptionId "<SubscriptionId>"
    
  2. 執行 Set-AzDataFactoryV2 Cmdlet 來建立資料處理站。 在執行命令之前,請先以您自己的值取代預留位置。

    $resourceGroupName = "<your resource group to create the factory>"
    $dataFactoryName = "<specify the name of data factory to create. It must be globally unique.>"
    Set-AzDataFactoryV2 -ResourceGroupName $resourceGroupName -Location "East US" -Name $dataFactoryName
    

    請注意下列幾點:

    • Azure Data Factory 的名稱必須是全域唯一的。 如果您收到下列錯誤,請變更名稱,然後再試一次。

      The specified Data Factory name 'ADFv2QuickStartDataFactory' is already in use. Data Factory names must be globally unique.
      
    • 若要建立 Data Factory 實例,您必須是 Azure 訂用帳戶的參與者或管理員管理員。

    • 如需 Data Factory 目前可用的 Azure 區域清單,請選取您在下列頁面上感興趣的區域,然後展開 [分析 ] 以找出 Data Factory 依區域 提供的產品。 資料處理站所使用的資料存放區(Azure 儲存體、Azure SQL 資料庫等)和計算(HDInsight 等)可以位於其他區域。

建立連結服務

在本教學課程中,您會分別為來源、接收和預備 Blob 建立三個連結服務,其中包括資料存放區的連線:

建立來源 Azure SQL 資料庫連結服務

  1. C:\ADFv2TutorialBulkCopy 資料夾中,使用下列內容建立名為 AzureSqlDatabaseLinkedService.json 的 JSON 檔案:(如果尚未存在,請建立 ADFv2TutorialBulkCopy 資料夾。

    重要

    將 servername、databasename > 、 << username > @ < servername >> 和 < password > 取代 < 為 Azure SQL 資料庫的值,再儲存檔案。

    {
        "name": "AzureSqlDatabaseLinkedService",
        "properties": {
            "type": "AzureSqlDatabase",
            "typeProperties": {
                "connectionString": "Server=tcp:<servername>.database.windows.net,1433;Database=<databasename>;User ID=<username>@<servername>;Password=<password>;Trusted_Connection=False;Encrypt=True;Connection Timeout=30"
            }
        }
    }
    
  2. Azure PowerShell 中,切換至 ADFv2TutorialBulkCopy 資料夾。

  3. 執行 Set-AzDataFactoryV2LinkedService Cmdlet 來建立連結的服務: AzureSqlDatabaseLinkedService

    Set-AzDataFactoryV2LinkedService -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "AzureSqlDatabaseLinkedService" -File ".\AzureSqlDatabaseLinkedService.json"
    

    以下是範例輸出:

    LinkedServiceName : AzureSqlDatabaseLinkedService
    ResourceGroupName : <resourceGroupName>
    DataFactoryName   : <dataFactoryName>
    Properties        : Microsoft.Azure.Management.DataFactory.Models.AzureSqlDatabaseLinkedService
    

建立接收 Azure Synapse Analytics 連結服務

  1. 在 C:\ADFv2TutorialBulkCopy 資料夾中建立名為 AzureSqlDWLinkedService.json 的 JSON 檔案,內容如下:

    重要

    將 servername、databasename > 、 << username > @ < servername >> 和 < password > 取代 < 為 Azure SQL 資料庫的值,再儲存檔案。

    {
        "name": "AzureSqlDWLinkedService",
        "properties": {
            "type": "AzureSqlDW",
            "typeProperties": {
                "connectionString": "Server=tcp:<servername>.database.windows.net,1433;Database=<databasename>;User ID=<username>@<servername>;Password=<password>;Trusted_Connection=False;Encrypt=True;Connection Timeout=30"
            }
        }
    }
    
  2. 若要建立連結服務: AzureSqlDWLinkedService ,請執行 Set-AzDataFactoryV2LinkedService Cmdlet。

    Set-AzDataFactoryV2LinkedService -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "AzureSqlDWLinkedService" -File ".\AzureSqlDWLinkedService.json"
    

    以下是範例輸出:

    LinkedServiceName : AzureSqlDWLinkedService
    ResourceGroupName : <resourceGroupName>
    DataFactoryName   : <dataFactoryName>
    Properties        : Microsoft.Azure.Management.DataFactory.Models.AzureSqlDWLinkedService
    

建立預備Azure 儲存體連結服務

在本教學課程中,您會使用 Azure Blob 儲存體作為過渡暫存區域,以啟用 PolyBase 以提升複製效能。

  1. 在 C:\ADFv2TutorialBulkCopy 資料夾中建立名為 Azure儲存體LinkedService.json 的 JSON 檔案,內容如下:

    重要

    將 accountName > 和 < accountKey > 取代 < 為 Azure 儲存體帳戶的名稱和金鑰,再儲存檔案。

    {
        "name": "AzureStorageLinkedService",
        "properties": {
            "type": "AzureStorage",
            "typeProperties": {
                "connectionString": "DefaultEndpointsProtocol=https;AccountName=<accountName>;AccountKey=<accountKey>"
            }
        }
    }
    
  2. 若要建立連結服務: Azure儲存體LinkedService ,請執行 Set-AzDataFactoryV2LinkedService Cmdlet。

    Set-AzDataFactoryV2LinkedService -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "AzureStorageLinkedService" -File ".\AzureStorageLinkedService.json"
    

    以下是範例輸出:

    LinkedServiceName : AzureStorageLinkedService
    ResourceGroupName : <resourceGroupName>
    DataFactoryName   : <dataFactoryName>
    Properties        : Microsoft.Azure.Management.DataFactory.Models.AzureStorageLinkedService
    

建立資料集

在本教學課程中,您會建立來源和接收資料集,以指定儲存資料的位置:

建立來源SQL 資料庫的資料集

  1. 在 C:\ADFv2TutorialBulkCopy 資料夾中建立名為 AzureSqlDatabaseDataset.json 的 JSON 檔案,內容如下。 「tableName」 是虛擬的,您稍後會在複製活動中使用 SQL 查詢來擷取資料。

    {
        "name": "AzureSqlDatabaseDataset",
        "properties": {
            "type": "AzureSqlTable",
            "linkedServiceName": {
                "referenceName": "AzureSqlDatabaseLinkedService",
                "type": "LinkedServiceReference"
            },
            "typeProperties": {
                "tableName": "dummy"
            }
        }
    }
    
  2. 若要建立資料集: AzureSqlDatabaseDataset ,請執行 Set-AzDataFactoryV2Dataset Cmdlet。

    Set-AzDataFactoryV2Dataset -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "AzureSqlDatabaseDataset" -File ".\AzureSqlDatabaseDataset.json"
    

    以下是範例輸出:

    DatasetName       : AzureSqlDatabaseDataset
    ResourceGroupName : <resourceGroupname>
    DataFactoryName   : <dataFactoryName>
    Structure         :
    Properties        : Microsoft.Azure.Management.DataFactory.Models.AzureSqlTableDataset
    

建立接收 Azure Synapse Analytics 的資料集

  1. 在 C:\ADFv2TutorialBulkCopy 資料夾中建立名為 AzureSqlDWDataset.json 的 JSON 檔案,內容如下:「tableName」 設定為參數,稍後參考此資料集的複製活動會將實際值傳遞至資料集。

    {
        "name": "AzureSqlDWDataset",
        "properties": {
            "type": "AzureSqlDWTable",
            "linkedServiceName": {
                "referenceName": "AzureSqlDWLinkedService",
                "type": "LinkedServiceReference"
            },
            "typeProperties": {
                "tableName": {
                    "value": "@{dataset().DWTableName}",
                    "type": "Expression"
                }
            },
            "parameters":{
                "DWTableName":{
                    "type":"String"
                }
            }
        }
    }
    
  2. 若要建立資料集: AzureSqlDWDataset ,請執行 Set-AzDataFactoryV2Dataset Cmdlet。

    Set-AzDataFactoryV2Dataset -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "AzureSqlDWDataset" -File ".\AzureSqlDWDataset.json"
    

    以下是範例輸出:

    DatasetName       : AzureSqlDWDataset
    ResourceGroupName : <resourceGroupname>
    DataFactoryName   : <dataFactoryName>
    Structure         :
    Properties        : Microsoft.Azure.Management.DataFactory.Models.AzureSqlDwTableDataset
    

建立管線

在本教學課程中,您會建立兩個管線:

建立管線 「IterateAndCopySQLTables」

此管線會採用資料表清單做為參數。 針對清單中的每個資料表,它會使用分段複製和 PolyBase,將資料從 Azure SQL 資料庫中的資料表複製到 Azure Synapse Analytics。

  1. 在 C:\ADFv2TutorialBulkCopy 資料夾中建立名為 IterateAndCopySQLTables.json 的 JSON 檔案,內容如下:

    {
        "name": "IterateAndCopySQLTables",
        "properties": {
            "activities": [
                {
                    "name": "IterateSQLTables",
                    "type": "ForEach",
                    "typeProperties": {
                        "isSequential": "false",
                        "items": {
                            "value": "@pipeline().parameters.tableList",
                            "type": "Expression"
                        },
                        "activities": [
                            {
                                "name": "CopyData",
                                "description": "Copy data from Azure SQL Database to Azure Synapse Analytics",
                                "type": "Copy",
                                "inputs": [
                                    {
                                        "referenceName": "AzureSqlDatabaseDataset",
                                        "type": "DatasetReference"
                                    }
                                ],
                                "outputs": [
                                    {
                                        "referenceName": "AzureSqlDWDataset",
                                        "type": "DatasetReference",
                                        "parameters": {
                                            "DWTableName": "[@{item().TABLE_SCHEMA}].[@{item().TABLE_NAME}]"
                                        }
                                    }
                                ],
                                "typeProperties": {
                                    "source": {
                                        "type": "SqlSource",
                                        "sqlReaderQuery": "SELECT * FROM [@{item().TABLE_SCHEMA}].[@{item().TABLE_NAME}]"
                                    },
                                    "sink": {
                                        "type": "SqlDWSink",
                                        "preCopyScript": "TRUNCATE TABLE [@{item().TABLE_SCHEMA}].[@{item().TABLE_NAME}]",
                                        "allowPolyBase": true
                                    },
                                    "enableStaging": true,
                                    "stagingSettings": {
                                        "linkedServiceName": {
                                            "referenceName": "AzureStorageLinkedService",
                                            "type": "LinkedServiceReference"
                                        }
                                    }
                                }
                            }
                        ]
                    }
                }
            ],
            "parameters": {
                "tableList": {
                    "type": "Object"
                }
            }
        }
    }
    
  2. 若要建立管線: IterateAndCopySQLTables ,請執行 Set-AzDataFactoryV2Pipeline Cmdlet。

    Set-AzDataFactoryV2Pipeline -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "IterateAndCopySQLTables" -File ".\IterateAndCopySQLTables.json"
    

    以下是範例輸出:

    PipelineName      : IterateAndCopySQLTables
    ResourceGroupName : <resourceGroupName>
    DataFactoryName   : <dataFactoryName>
    Activities        : {IterateSQLTables}
    Parameters        : {[tableList, Microsoft.Azure.Management.DataFactory.Models.ParameterSpecification]}
    

建立管線 「GetTableListAndTriggerCopyData」

此管線會執行兩個步驟:

  • 查閱 Azure SQL 資料庫系統資料表,以取得要複製的資料表清單。
  • 觸發管線 「IterateAndCopySQLTables」 以執行實際的資料複製。
  1. 在 C:\ADFv2TutorialBulkCopy 資料夾中建立名為 GetTableListAndTriggerCopyData.json 的 JSON 檔案,內容如下:

    {
        "name":"GetTableListAndTriggerCopyData",
        "properties":{
            "activities":[
                { 
                    "name": "LookupTableList",
                    "description": "Retrieve the table list from Azure SQL dataabse",
                    "type": "Lookup",
                    "typeProperties": {
                        "source": {
                            "type": "SqlSource",
                            "sqlReaderQuery": "SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.TABLES WHERE TABLE_TYPE = 'BASE TABLE' and TABLE_SCHEMA = 'SalesLT' and TABLE_NAME <> 'ProductModel'"
                        },
                        "dataset": {
                            "referenceName": "AzureSqlDatabaseDataset",
                            "type": "DatasetReference"
                        },
                        "firstRowOnly": false
                    }
                },
                {
                    "name": "TriggerCopy",
                    "type": "ExecutePipeline",
                    "typeProperties": {
                        "parameters": {
                            "tableList": {
                                "value": "@activity('LookupTableList').output.value",
                                "type": "Expression"
                            }
                        },
                        "pipeline": {
                            "referenceName": "IterateAndCopySQLTables",
                            "type": "PipelineReference"
                        },
                        "waitOnCompletion": true
                    },
                    "dependsOn": [
                        {
                            "activity": "LookupTableList",
                            "dependencyConditions": [
                                "Succeeded"
                            ]
                        }
                    ]
                }
            ]
        }
    }
    
  2. 若要建立管線: GetTableListAndTriggerCopyData ,請執行 Set-AzDataFactoryV2Pipeline Cmdlet。

    Set-AzDataFactoryV2Pipeline -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "GetTableListAndTriggerCopyData" -File ".\GetTableListAndTriggerCopyData.json"
    

    以下是範例輸出:

    PipelineName      : GetTableListAndTriggerCopyData
    ResourceGroupName : <resourceGroupName>
    DataFactoryName   : <dataFactoryName>
    Activities        : {LookupTableList, TriggerCopy}
    Parameters        :
    

啟動和監視管線執行

  1. 啟動主要 「GetTableListAndTriggerCopyData」 管線的管線執行,並擷取管線執行識別碼以供日後監視。 在下方,它會觸發管線 「IterateAndCopySQLTables」 的執行,如 ExecutePipeline 活動中所指定。

    $runId = Invoke-AzDataFactoryV2Pipeline -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -PipelineName 'GetTableListAndTriggerCopyData'
    
  2. 執行下列腳本以持續檢查管線 GetTableListAndTriggerCopyData 的執行狀態,並列印出最終的管線 執行和活動執行結果。

    while ($True) {
        $run = Get-AzDataFactoryV2PipelineRun -ResourceGroupName $resourceGroupName -DataFactoryName $DataFactoryName -PipelineRunId $runId
    
        if ($run) {
            if ($run.Status -ne 'InProgress') {
                Write-Host "Pipeline run finished. The status is: " $run.Status -ForegroundColor "Yellow"
                Write-Host "Pipeline run details:" -ForegroundColor "Yellow"
                $run
                break
            }
            Write-Host  "Pipeline is running...status: InProgress" -ForegroundColor "Yellow"
        }
    
        Start-Sleep -Seconds 15
    }
    
    $result = Get-AzDataFactoryV2ActivityRun -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -PipelineRunId $runId -RunStartedAfter (Get-Date).AddMinutes(-30) -RunStartedBefore (Get-Date).AddMinutes(30)
    Write-Host "Activity run details:" -ForegroundColor "Yellow"
    $result
    

    以下是範例執行的輸出:

    Pipeline run details:
    ResourceGroupName : <resourceGroupName>
    DataFactoryName   : <dataFactoryName>
    RunId             : 0000000000-00000-0000-0000-000000000000
    PipelineName      : GetTableListAndTriggerCopyData
    LastUpdated       : 9/18/2017 4:08:15 PM
    Parameters        : {}
    RunStart          : 9/18/2017 4:06:44 PM
    RunEnd            : 9/18/2017 4:08:15 PM
    DurationInMs      : 90637
    Status            : Succeeded
    Message           : 
    
    Activity run details:
    ResourceGroupName : <resourceGroupName>
    DataFactoryName   : <dataFactoryName>
    ActivityName      : LookupTableList
    PipelineRunId     : 0000000000-00000-0000-0000-000000000000
    PipelineName      : GetTableListAndTriggerCopyData
    Input             : {source, dataset, firstRowOnly}
    Output            : {count, value, effectiveIntegrationRuntime}
    LinkedServiceName : 
    ActivityRunStart  : 9/18/2017 4:06:46 PM
    ActivityRunEnd    : 9/18/2017 4:07:09 PM
    DurationInMs      : 22995
    Status            : Succeeded
    Error             : {errorCode, message, failureType, target}
    
    ResourceGroupName : <resourceGroupName>
    DataFactoryName   : <dataFactoryName>
    ActivityName      : TriggerCopy
    PipelineRunId     : 0000000000-00000-0000-0000-000000000000
    PipelineName      : GetTableListAndTriggerCopyData
    Input             : {pipeline, parameters, waitOnCompletion}
    Output            : {pipelineRunId}
    LinkedServiceName : 
    ActivityRunStart  : 9/18/2017 4:07:11 PM
    ActivityRunEnd    : 9/18/2017 4:08:14 PM
    DurationInMs      : 62581
    Status            : Succeeded
    Error             : {errorCode, message, failureType, target}
    
  3. 您可以取得管線 「 IterateAndCopySQLTables 」 的執行識別碼,並檢查詳細的活動執行結果,如下所示。

    Write-Host "Pipeline 'IterateAndCopySQLTables' run result:" -ForegroundColor "Yellow"
    ($result | Where-Object {$_.ActivityName -eq "TriggerCopy"}).Output.ToString()
    

    以下是範例執行的輸出:

    {
        "pipelineRunId": "7514d165-14bf-41fb-b5fb-789bea6c9e58"
    }
    
    $result2 = Get-AzDataFactoryV2ActivityRun -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -PipelineRunId <copy above run ID> -RunStartedAfter (Get-Date).AddMinutes(-30) -RunStartedBefore (Get-Date).AddMinutes(30)
    $result2
    
  4. 連線至您的接收 Azure Synapse Analytics,並確認資料已正確從 Azure SQL 資料庫複製。

您在本教學課程中執行下列步驟:

  • 建立資料處理站。
  • 建立 Azure SQL 資料庫、Azure Synapse Analytics 和Azure 儲存體連結服務。
  • 建立 Azure SQL 資料庫和 Azure Synapse Analytics 資料集。
  • 建立管線來查閱要複製的資料表,並建立另一個管線來執行實際的複製作業。
  • 啟動管線執行。
  • 監視管線和活動執行。

前進到下列教學課程,以瞭解如何以累加方式將資料從來源複製到目的地: