From 96493e059bb804e06a7a4abbed8a63722408ffe4 Mon Sep 17 00:00:00 2001 From: James Mueller <97551379+jamesmmueller@users.noreply.github.com> Date: Fri, 11 Mar 2022 16:09:38 -0600 Subject: [PATCH] ConvertFrom-ExcelToSQLInsert fix single quotes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- Public/ConvertFrom-ExcelToSQLInsert.ps1 | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Public/ConvertFrom-ExcelToSQLInsert.ps1 b/Public/ConvertFrom-ExcelToSQLInsert.ps1 index b468d8b..858544e 100644 --- a/Public/ConvertFrom-ExcelToSQLInsert.ps1 +++ b/Public/ConvertFrom-ExcelToSQLInsert.ps1 @@ -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 } -} \ No newline at end of file +}