ConvertFrom-ExcelToSQLInsert fix single quotes

If data in the Excel file contains single quotes, then the insert will bomb as it will be malformed. Quotes would need escaped. Not all languages will support the same escape method, so I recommend it being set by an optional parameter.

Example of what will fail:
  Name
  -----------
  Fry's

INSERT INTO [Name] Values ( 'Fry's' ) 

Corrected for quotes (such as needing to escape a single quote with an additional single quote)

INSERT INTO [Name] Values ('Fry''s') 


Example code:
$ConvertToSqlParams = @{TableName = ‘dbo.Names’
Path = ‘C:\temp\data.xlsx’
ConvertEmptyStringsToNull = $true
UseMSSQLSyntax = $true
SingleQuoteStyle = "''"
}

$SQLInsert = ConvertFrom-ExcelToSqlInsert @ConvertToSqlParams
This commit is contained in:
James Mueller
2022-03-11 16:09:38 -06:00
committed by GitHub
parent cb7f2a06f4
commit 96493e059b

View File

@@ -16,12 +16,15 @@ function ConvertFrom-ExcelToSQLInsert {
[switch]$NoHeader,
[switch]$DataOnly,
[switch]$ConvertEmptyStringsToNull,
[switch]$UseMsSqlSyntax
[switch]$UseMsSqlSyntax,
[Parameter(Mandatory = $false)]
$SingleQuoteStyle
)
$null = $PSBoundParameters.Remove('TableName')
$null = $PSBoundParameters.Remove('ConvertEmptyStringsToNull')
$null = $PSBoundParameters.Remove('UseMsSqlSyntax')
$null = $PSBoundParameters.Remove('SingleQuoteStyle')
$params = @{} + $PSBoundParameters
@@ -38,11 +41,16 @@ function ConvertFrom-ExcelToSQLInsert {
'NULL'
}
else {
"'" + $record.$propertyName + "'"
if ( $SingleQuoteStyle ) {
"'" + $record.$propertyName.ToString().Replace("'",${SingleQuoteStyle}) + "'"
}
else {
"'" + $record.$propertyName + "'"
}
}
}
$targetValues = ($values -join ", ")
"INSERT INTO {0} ({1}) Values({2});" -f $TableName, $ColumnNames, $targetValues
}
}
}