If have the following peace of C# code to write rows from a DataTable to my SQL table.
foreach (DataRow row in dataTable.Rows)
{
string insertSql = GenerateInsertSql(tableName, dataTable.Columns, row);
using SqlCommand insertCommand = new(insertSql, connection);
foreach (DataColumn column in dataTable.Columns)
{
if (row[column] == DBNull.Value)
{
insertCommand.Parameters.AddWithValue($"@{column.ColumnName}", DBNull.Value);
}
}
foreach (SqlParameter param in insertCommand.Parameters)
{
Trace.WriteLine($"Parameter: {param.ParameterName}, Value: {param.Value}, SqlValue: {param.SqlValue}");
}
insertCommand.ExecuteNonQuery();
}
The problem I’m struggeling with is no matter what I try I’m not able to get null values in datetime columns where null values are allowed. I tried it with adding command parameters but the result for columns containing a DBNull.Value is the default datetime value of ‘1900-01-01 00:00:00.000’. As I said for this columns Null values are allowed and the are no constraints on the columns turning Null values into this default datetime value.
In the traceline written I can see that Value == {} and SqlValue == {Null}
I also tried the same code with parameter value ‘1999-01-01 00:00:00.000, in that case both Value and SqlValue has this date value of ‘1999-01-01 00:00:00.000’ but in the database after executing this Insert command the value is again ‘1900-01-01 00:00:00.000’. So for me it looks like the parameters are ignored when executing the Insert command.