Posts Bulk Copy Data from Oracle to SQL Server via PowerShell
Post
Cancel

Bulk Copy Data from Oracle to SQL Server via PowerShell

https://www.mssqltips.com/sqlservertip/5149/bulk-copy-data-from-oracle-to-sql-server/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#simple sample
#copy table from Oracle table to SQL Server table
add-type -path 'C:\oracle\odp.net\managed\common\Oracle.ManagedDataAccess.dll';
#define oracle connection string
$conn_str = "User Id=system;Password=MyP@ssw0rd;Data Source=XE";
# query for oracle table
$qry = "select * from tblTest";
$adapter = new-object Oracle.ManagedDataAccess.Client.OracleDataAdapter($qry, $conn_str);
$dtbl = new-object System.Data.DataTable('tblTest');
#this Fill method will populate the $dtbl with the query $qry result
$adapter.Fill($dtbl);
#define sql server target instance
$sqlconn = "server=localhost\sql2016;database=mssqltips;trusted_connection=true";
$sqlbc = new-object system.data.sqlclient.Sqlbulkcopy($sqlconn);
$sqlbc.DestinationTableName="dbo.tblTest";
$sqlbc.WriteToServer($dtbl); 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#advanced sample
#copy table from Oracle table to SQL Server table
add-type -path 'C:\oracle\odp.net\managed\common\Oracle.ManagedDataAccess.dll';
#define oracle connectin string
$conn_str = "User Id=system;Password=MyP@ssw0rd;Data Source=XE";
# query for oracle table
$qry = "select dt, sales, name from tblTest";
# key (on the left side) is the source column while value (on the right side) is the target column
[hashtable] $mapping = @{'DT'='SaleDate'; 'SALES'='Sales'; 'NAME'='Name'};

$adapter = new-object Oracle.ManagedDataAccess.Client.OracleDataAdapter($qry, $conn_str);
$dtbl = new-object System.Data.DataTable('tblTest');
#this Fill method will populate the $dtbl with the query $qry result
$adapter.Fill($dtbl);
#define sql server target instance
$sqlconn = "server=localhost\sql2016;database=mssqltips;trusted_connection=true";
$sqlbc = new-object system.data.sqlclient.Sqlbulkcopy($sqlconn);
$sqlbc.DestinationTableName="dbo.tblTest2";

#need to tell $sqlbc the column mapping info
foreach ($k in $mapping.keys)
{
    $colMapping = new-object System.Data.SqlClient.SqlBulkCopyColumnMapping($k, $mapping[$k]);
    $sqlbc.ColumnMappings.Add($colMapping) | out-null
}
$sqlbc.WriteToServer($dtbl);

origin - http://www.pipiscrew.com/?p=10679 bulk-copy-data-from-oracle-to-sql-server-via-powershell

This post is licensed under CC BY 4.0 by the author.
Contents

Trending Tags