1

I have powershell script to insert values from an xml file into the sql database.

The issue I'm facing is that i cant seem to insert the values into the sql database, as the error states that the string value in data source is not getting converted to the uniqueidentifier type in target columns(which are basically the ScheduleId and AccountingPeriodCase_PK_ID columns in the sql database).

I tried changing the [guid] datatype during columns.add() to [uniqueidentifier] and all but they gave me errors.

Script:

$dataSource = $env:COMPUTERNAME;                                       
$database = "DataModel.PAModel" 

$connection = New-Object System.Data.SqlClient.SqlConnection;  #setting connection
$connection.ConnectionString = "Server=$dataSource;Database=$database;Integrated Security=True;";
$connection.Open();

$command = New-Object System.Data.SqlClient.SqlCommand;
$command.Connection = $connection;

$as = New-Object System.Data.SqlClient.SqlDataAdapter;
$as.SelectCommand = $command;
$filename = "C:\XML\apc.xml";            #file to be loaded into sql server database table

$ds = New-Object System.Data.DataSet;
$ds.ReadXml($filename);    #reading from the file -- line gives output InferSchema

$dt = New-Object System.Data.DataTable;

$dt.Columns.Add("StartTime",[datetime]);
$dt.Columns.Add("EndTime",[datetime]);
$dt.Columns.Add("Status",[int]);
$dt.Columns.Add("ProcessedTime",[datetime]);
$dt.Columns.Add("ScheduleId",[guid]);
$dt.Columns.Add("Model",[string]);
$dt.Columns.Add("ModelVersion",[string]);
$dt.Columns.Add("ModelVersionState",[string]);
$dt.Columns.Add("ModifiedTime",[datetime]);
$dt.Columns.Add("WriteBackLastRunTime",[datetime]);
$dt.Columns.Add("ModifiedBy",[string]);
$dt.Columns.Add("ModelType",[int]);
$dt.Columns.Add("IsTimeRange",[int]);
$dt.Columns.Add("WriteBackStatus",[int]);
$dt.Columns.Add("RetryWriteBack",[int]);
$dt.Columns.Add("NumOfRetry",[int]);
$dt.Columns.Add("FrequencyUnits",[int]);
$dt.Columns.Add("ScheduleType",[int]);
$dt.Columns.Add("CustomType",[int]);
#$dt.Columns.Add("ShiftStartTime",[datetime]);
#$dt.Columns.Add("StartWeekDay",[int]);
#$dt.Columns.Add("EndWeekDay",[int]);
$dt.Columns.Add("WritebackProcessedTime",[datetime]);
$dt.Columns.Add("DiagStatus",[int]);

$dc = New-Object System.Data.DataColumn;
$dc = $dt.Columns.Add("AccountingPeriodCase_PK_ID",[guid]);

$dc.AllowDBNull.Equals($false);
$dc.Unique.Equals($true);

$dt=$ds.Tables[0];

$bcp = New-Object "Data.SqlClient.SqlBulkCopy" $connection; #bulkcopy to the destination table.
$bcp.DestinationTableName = "dbo.AccountingPeriodCases";

#$bcp.ColumnMappings.Count;
$bcp.ColumnMappings.Clear();

$bcp.ColumnMappings.Add("StartTime","StartTime");
$bcp.ColumnMappings.Add("EndTime","EndTime");
$bcp.ColumnMappings.Add("Status","Status");
$bcp.ColumnMappings.Add("ProcessedTime","ProcessedTime");
$bcp.ColumnMappings.Add("ScheduleId","ScheduleId");
$bcp.ColumnMappings.Add("Model","Model");
$bcp.ColumnMappings.Add("ModelVersion","ModelVersion");
$bcp.ColumnMappings.Add("ModelVersionState","ModelVersionState");
$bcp.ColumnMappings.Add("ModifiedTime","ModifiedTime");
$bcp.ColumnMappings.Add("WriteBackLastRunTime","WriteBackLastRunTime");
$bcp.ColumnMappings.Add("ModifiedBy","ModifiedBy");
$bcp.ColumnMappings.Add("ModelType","ModelType");
$bcp.ColumnMappings.Add("IsTimeRange","IsTimeRange");
$bcp.ColumnMappings.Add("WriteBackStatus","WriteBackStatus");
$bcp.ColumnMappings.Add("RetryWriteBack","RetryWriteBack");
$bcp.ColumnMappings.Add("NumOfRetry","NumOfRetry");
$bcp.ColumnMappings.Add("FrequencyUnits","FrequencyUnits");
$bcp.ColumnMappings.Add("ScheduleType","ScheduleType");
$bcp.ColumnMappings.Add("CustomType","CustomType");
#$bcp.ColumnMappings.Add("ShiftStartTime","ShiftStartTime");
#$bcp.ColumnMappings.Add("StartWeekDay","StartWeekDay");
#$bcp.ColumnMappings.Add("EndWeekDay","EndWeekDay");
$bcp.ColumnMappings.Add("WritebackProcessedTime","WritebackProcessedTime");
$bcp.ColumnMappings.Add("DiagStatus","DiagStatus");
$bcp.ColumnMappings.Add("AccountingPeriodCase_PK_ID","AccountingPeriodCase_PK_ID");

#$bcp.ColumnMappings.Count;


if ($connection.State -ne [Data.ConnectionState]::Open) {

    "Connection to DB is not open.";

    Exit;

}

$bcp.WriteToServer($dt);        #writing to server 
$bcp.ColumnMappings.Clear();
$connection.Close();

Error:

Exception calling "WriteToServer" with "1" argument(s): "The given value of type String from the  data source cannot be converted to type uniqueidentifier of the specified target column." At C:\Documents\DCT\SavedScripts\XMLtoDB\AccountingPeriodCases\xAccountingPeriodCases .ps1:96 char:1
+ $bcp.WriteToServer($dt);        #writing to server
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException

The sql database table have the following columns: enter image description here

Could you help me resolve the error?

The values of ScheduleId and AccountingPeriodCases_PK_ID :

enter image description here

B21
  • 37
  • 1
  • 9
  • Apparently the value of either `ScheduleId` or `AccountingPeriodCase_PK_ID` can't be [converted](https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-type-conversion-database-engine?view=sql-server-2017) to type [`uniqueidentifier`](https://learn.microsoft.com/en-us/sql/t-sql/data-types/uniqueidentifier-transact-sql?view=sql-server-2017). Check the values of those columns. – Ansgar Wiechers May 02 '18 at 08:03
  • Those are the values for the two columns – B21 May 02 '18 at 09:40
  • Looks OK to me. Did you try converting them to GUID objects before importing the data table? – Ansgar Wiechers May 02 '18 at 09:43
  • u mean [GUID]::NewGuid()? – B21 May 02 '18 at 09:48
  • 1
    `$dt=$ds.Tables[0];` replaces the contents of the variable `$dt` with the first table in the `DataSet`. In other words, all those columns you've been adding are completely ignored, you're entirely at the mercy of what `$ds.ReadXml($filename)` returns. You'll need to change the XML so it has proper types, or else avoid `ReadXml` altogether, parse the XML using PowerShell and call `.Rows.Add` on your own table. – Jeroen Mostert May 02 '18 at 09:48
  • No, I mean `[guid]'4bd44704-e943-48dc-a869-faa5ac0b2adf'`. – Ansgar Wiechers May 02 '18 at 09:50
  • @JeroenMostert - Could you please help me out with that alternative as to what are the changes i should make here? – B21 May 02 '18 at 09:52
  • @AnsgarWiechers - I had tried it but i didn't get any change in output.. – B21 May 02 '18 at 09:53
  • 1
    It's not clear what's in your XML, so that would be hard... An excerpt with the markup for a row might help. Note that PowerShell has extensive XML support; simply doing `[xml] (Get-Content $filename)` will give you an object you can examine and use. Resources on how to process XML in PowerShell are plentiful. – Jeroen Mostert May 02 '18 at 09:54
  • @JeroenMostert Ill just try checking it up and ill get back if i have any queries.. But are u sure that the error im obtaining is because of that? – B21 May 02 '18 at 09:56
  • As sure as my psychic debugging skills allow me to be. Try `$bcp.WriteToServer($ds.Tables[0])` directly. It should give you the same error, proving that the combination of the XML and `DataSet.ReadXml` give a table with contents that can't be mapped properly. As to why that is, it would require looking at the XML. – Jeroen Mostert May 02 '18 at 10:05
  • @JeroenMostert - Thank you for patiently helping me.. i will check and get back to you :) – B21 May 02 '18 at 10:06

0 Answers0