I know I can do all this via SSMA quite quickly, but I wanted to see if I could do it efficiently in PowerShell myself as a little project.
Basically, the entire script takes tables from an Access database and creates a database in SQL Server with the same data. Everything from creating the table structure to cleansing the data is running quick. The slow part is inserting the data, which was inevitable but I want to see if I can make it a bit faster.
Here is the code:
<# Insert data into tables #>
function Insert_Data {
param ( $data, $tableName )
$columns = ($data.PSObject.Properties | where {$_.name -eq "Columns"}).value.columnName | Sort-Object
$Insert = "INSERT INTO $tableName
VALUES "
$i = 0
$x = 0
foreach ($item in $data) {
$Insert += "
("
foreach ($item in $columns) {
$Insert += "'" + $data.rows[$x].$item + "',"
}
$Insert = $Insert.Substring(0,$Insert.Length-1)
$Insert += "),"
if ($i -eq 900) {
$Insert = $Insert.Substring(0,$Insert.Length-1)
$Insert += ";"
Invoke-SQLCMD -Query $Insert -ServerInstance "." -database tmpAccessData -erroraction "Stop"
$Insert = "INSERT INTO $tableName
VALUES "
$i = 0
}
$i++
$x++
}
$Insert = $Insert.Substring(0,$Insert.Length-1)
$Insert += ";"
Invoke-SQLCMD -Query $Insert -ServerInstance "." -database tmpAccessData -erroraction "Stop"
Remove-Variable -Name data
}
It generates a large SQL query and inserts that into the specified table once it hits 900 values or the end of the Access table.
The data variable is the full Access table pulled into an Object:
$data_Clients = Get-AccessData -Query "SELECT * FROM Client" -Source $($settings.FastrackFiles.access_Fastrack);
And tablename is just the name of the table in the destination SQL database.