Skip to content

Instantly share code, notes, and snippets.

@mattstrom
Last active May 9, 2016 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattstrom/e12519e10763c4b0e56b07664e480812 to your computer and use it in GitHub Desktop.
Save mattstrom/e12519e10763c4b0e56b07664e480812 to your computer and use it in GitHub Desktop.
Converts an array of objects into a SQL insert statement.
<#
.SYNOPSIS
Converts an array of objects into a SQL insert statement.
.EXAMPLE
Import-Csv -Path language.csv -Delimiter `| -Header @("col1", "col2") | Convert-ToInsertQuery -TableName table1 -DefaultType varchar -DataTypes @{ col1 = "int" }
#>
function Convert-ToInsertQuery {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true)]
[array] $Items,
[string] $TableName,
[ValidateSet("number", "string")]
[string] $DefaultType = "string",
[hashtable] $DataTypes = @{}
)
BEGIN {
$_items = @()
}
PROCESS {
$_items += $_
}
END {
$lines = @()
$columns = @()
# Collect column names from property names.
if ($_items.Count -ne 0) {
$_items[0].PSObject.Properties | %{
$columns += $_.Name
}
}
"INSERT INTO $TableName ($($columns -join ",")) VALUES "
for ($i = 0; $i -lt $_items.Count; $i++) {
$item = $_items[$i]
$properties = @()
$item.PSObject.Properties | %{
$name = $_.Name
$value = $_.Value
$dataType = if ($DataTypes[$name] -ne $null) { $DataTypes[$name] } else { $DefaultType }
switch ($DataTypes[$name]) {
"number" { $value = $value }
"string" { $value = "'$value'" }
default { $value = "'$value'" }
}
$properties += "$value"
}
$lines += "($($properties -join ","))"
}
($lines -join ",`r`n") + ";"
}
}
$file = "vs_market\EN.dat"
$header = @(
"record_type";
"content_indicator";
"file_number";
"registration_number";
"unique_system_identifier";
"entity_type";
"entity_type_code";
"entity_type_other";
"licensee_id";
"entity_name";
"first_name";
"mi";
"last_name";
"suffix";
"phone";
"fax";
"internet_address";
"street_address";
"street_address2";
"po_box";
"city";
"state";
"zip_code";
"attention";
"frn";
);
Import-Csv -Path $file -Delimiter `| -Header $header |
# Select -First 10 | # Uncomment the beginning of this line to test the conversion with a small subset
Convert-ToInsertQuery -TableName vs_market -DefaultType string -DataTypes @{ unique_system_identifier = "number" } |
Set-Content output.sql
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment