Skip to content

Commit df8deb2

Browse files
committedFeb 26, 2020
Add UPSERT function for Oracle
1 parent 5ae6602 commit df8deb2

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed
 

‎Public/Invoke-OracleCmd.ps1

+1-1
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ function Invoke-OracleCmd {
162162
try {
163163
$Connection.Open()
164164
} catch {
165-
Write-Log -Type "ERROR" -Object "Unable to reach database $($Hostname):$PortNumber/$Instance"
165+
Write-Log -Type "ERROR" -Object "Unable to reach database $($Hostname):$PortNumber/$ServiceName"
166166
return $Error
167167
}
168168
# Create SQL command

‎Public/Write-InsertOrUpdate.ps1

+31-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ function Write-InsertOrUpdate {
4444
File name: Write-InsertOrUpdate.ps1
4545
Author: Florian Carrier
4646
Creation date: 15/10/2019
47-
Last modified: 10/02/2020
47+
Last modified: 26/02/2020
4848
#>
4949
[CmdletBinding (
5050
SupportsShouldProcess = $true
@@ -111,6 +111,36 @@ function Write-InsertOrUpdate {
111111
Process {
112112
switch ($Vendor) {
113113
"Oracle" {
114+
# Define existence check
115+
foreach($Key in $PrimaryKey) {
116+
if ($PrimaryKeyCheck -eq $null) { $PrimaryKeyCheck = "$Key = $($Fields.$Key)" }
117+
else { $PrimaryKeyCheck += " AND $Key = $($Fields.$Key)" }
118+
}
119+
$Check = [System.String]::Concat("MERGE INTO $Table USING dual ON (", $PrimaryKeyCheck, ")")
120+
121+
# Loop through fields
122+
foreach ($Field in $Fields.GetEnumerator()) {
123+
# Select update values
124+
if ($Field.Key -NotIn $PrimaryKey) {
125+
if ($UpdateValues -eq $null) { $UpdateValues = "$($Field.Key) = $($Field.Value)" }
126+
else { $UpdateValues += ", $($Field.Key) = $($Field.Value)" }
127+
}
128+
# Set insert fields
129+
if ($InsertFields -eq $null) { $InsertFields = "$($Field.Key)" }
130+
else { $InsertFields += ", $($Field.Key)" }
131+
# Set insert values
132+
if ($InsertValues -eq $null) { $InsertValues = "$($Field.Value)" }
133+
else { $InsertValues += ", $($Field.Value)" }
134+
}
135+
136+
# Construct update query
137+
$Update = [System.String]::Concat("WHEN MATCHED THEN UPDATE SET ", $UpdateValues)
138+
# Construct insert query
139+
$Insert = [System.String]::Concat("WHEN NOT MATCHED THEN INSERT (", $InsertFields, ") VALUES (", $InsertValues, ")")
140+
141+
# Construct whole SQL query
142+
$Query = [System.String]::Concat($Check, "`n", $Update, "`n", $Insert)
143+
114144
# TODO
115145
}
116146
"SQLServer" {

0 commit comments

Comments
 (0)
Please sign in to comment.