Skip to content

Insert object containing DateTime #9

Description

@jasoncocks

When Write-ObjectToSQL when inserting a DateTime, the table is created correctly but subsequent INSERTs rely on DateTime.ToString() ... this has local issues ...

(Get-Date).ToString()
21/06/2018 18:33:17

In order to insert date/time into SQL Server reliably as a nvarchar, Write-ObjectToSQL should convert date/time objects into the SQL Server default date/time format.

E.g.

I have modified the function including ...
$dateformattypes = @{
# PS datatype = SQL data type
'System.DateTime' = 'datetime';
'datetime' = 'datetime';
}

...
if ( $numbertypes.ContainsKey( $datatype ) ){
$null = $strBuilderColumns.Append(", $quoteFirst$prekey$($key.Replace(' ','_'))$quoteLast")

                if ($($InputObject.$key) -ne $null){
                    if ($datatype -eq 'timespan' -or $datatype -eq 'System.TimeSpan') {
                        Write-Verbose "Timespan found ($key). Converting to ticks."
                        $null = $strBuilderValues.Append(", $(($InputObject.$key).Ticks)")
                    }else{
                        $null = $strBuilderValues.Append(", $($InputObject.$key)")
                    }
                    
                }else{
                    $null = $strBuilderValues.Append(", NULL")
                }
            **}elseif ( $dateformattypes.ContainsKey( $datatype ) ){
                $null = $strBuilderColumns.Append(", $quoteFirst$prekey$($key.Replace(' ','_'))$quoteLast")
                $strtmp = $InputObject.$key.ToString("yyyy-MM-dd HH:mm:ss.fff")
                if ($ConnectionString){ 
                    $null = $strBuilderValues.Append(", '$strtmp'")
                }else{
                    $null = $strBuilderValues.Append(", N'$strtmp'")
                }**
            }elseif ( $stringtypes.ContainsKey( $datatype ) ){
                $null = $strBuilderColumns.Append(", $quoteFirst$prekey$($key.Replace(' ','_'))$quoteLast")
                $strtmp = $InputObject.$key -replace "'", "''"
                if ($ConnectionString){ 
                    $null = $strBuilderValues.Append(", '$strtmp'")
                }else{
                    $null = $strBuilderValues.Append(", N'$strtmp'")
                }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions