-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConvertTo-SQLSelect
71 lines (52 loc) · 2.12 KB
/
ConvertTo-SQLSelect
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
function ConvertTo-SQLSelect {
[CmdletBinding()]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 0
)]
$Data
)
begin {
$sqlStmt = [Text.StringBuilder]::new()
$null = $sqlStmt.AppendLine('SELECT')
[bool] $needsHeader = $true
[bool] $needsStartingComma = $false
$captureAll = [System.Collections.Generic.List[object]]::new()
}
process {
($Data).ForEach({ $captureAll.Add($_) })
}
end {
$headers = ($data | Get-Member -MemberType NoteProperty, Property).Name
foreach ($header in $headers) {
<#
Why the PadLeft and weird 5-2*bool variable? Formatting.
Why the (Option1, Option2)[bool variable]? Chooses an option based on bool.
#>
$headerLine = ''.PadLeft(5 - (2 * $needsStartingComma)) + ('', ', ')[$needsStartingComma] + "[$($header)]"
$null = $sqlStmt.AppendLine($headerLine)
$needsStartingComma = $true
}
$needsStartingComma = $false
$null = $sqlStmt.AppendLine('FROM (VALUES')
foreach ($dataRow in $captureAll) {
$rowInsert = [Text.StringBuilder]::new()
$startBracket = ''.PadLeft(5 - (2 * $needsStartingComma)) + ('', ', ')[$needsStartingComma] + '('
$null = $rowInsert.Append($startBracket)
[bool] $needsRowComma = $false
foreach ($column in $headers) {
Write-Verbose "Row: $dataRow - Column: $column - Value $($dataRow.$column)"
$rowLine = ('', ', ')[$needsRowComma] + "'$(($dataRow.$column) -replace "'", "''")'"
$null = $rowInsert.Append($rowLine)
$needsRowComma = $true
}
$null = $rowInsert.Append(')')
$null = $sqlStmt.AppendLine($rowInsert.ToString())
$needsStartingComma = $true
}
$null = $sqlStmt.AppendLine(") X ([$($headers -join '], [')])")
$sqlStmt.ToString()
}
}