Powershell Script to export/import SQL Server tables

Frank Anellia 41 Reputation points
2021-02-22T19:53:35.477+00:00

Hello,

I'm looking to automate a SQL Server export/import job. The tables are located on Azure SQL Server so I was thinking of using a PS script for automation purposes. The job will run on a monthly basis to copy files from a few tables in one database to the same tables into a database on a different server.

I'm looking for a starting point, and was having trouble finding anything online.

Any help would be greatly appreciated.

Thanks,
Frank

Azure SQL Database
Windows for business Windows Server User experience PowerShell
Developer technologies Transact-SQL
SQL Server Other
{count} votes

Accepted answer
  1. AmeliaGu-MSFT 14,006 Reputation points Microsoft External Staff
    2021-02-23T05:57:17.577+00:00

    Hi FrankAnellia-9381,

    You can try to use SqlBulkCopy with Powershell to copy data from tables in one database to the same tables into a database on a different server. Please refer to this article which might help.
    You also can use powershell dbatools Copy-DbaDbTableData to copy data.
    For example, to copy all the data from table dbo.test_table (2-part name) in database dbatools_from on sql1 to table test_table in database dbatools_from on sql2:

    Copy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -Table dbo.test_table  
    

    Please refer to Copy-DbaDbTableData for more details.

    Best Regards,
    Amelia


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


2 additional answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2021-02-22T20:43:56+00:00

    Google.
    powershell sql server import
    powershell sql server export


  2. Jeffrey Williams 1,896 Reputation points
    2021-02-22T21:04:56.417+00:00

    You can start with Invoke-SqlCmd - something like:

    $sourceData = Invoke-SqlCmd -ServerInstance ... -Query "...";
    

    You can then pipe that to Export-Csv to create a CSV file.

    Then use BCP or BULK INSERT on the destination to read in the CSV file.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.