What I want to do is basically take any generic DataTable and then Convert all the DateTime columns into SqlDateTime Columns. (i.e if the datetime column value = datetime.MinValue then Set it to SqlDateTime.Null)
Is there anyway I can do this without altering the original datatable (i.e withoutadding computed columns ) or having to parse through then entire datatable row by row?
The reason I want to do this is because I need to feed this Datatable into a SQLBulkCopy method, which would write them all together into the database. The problem with using datetime field is that it throws an error at the time of upload.
Agen开发者_运维问答tX
Well, the best i could come up with was this,
I know it is copying the datatable row by row, I believe it can be done more elegantly with LINQ ,
any one else has an answer?
Dim dtOut As DataTable = dt.Clone()
For Each c As DataColumn In dtOut.Columns
If c.DataType.FullName = GetType(DateTime).FullName Then
c.DataType = GetType(SqlTypes.SqlDateTime)
End If
Next
dtOut.BeginLoadData()
Dim drtmp As DataRow
For Each dr As DataRow In dt.Rows
drtmp = dtOut.NewRow()
For Each dc As DataColumn In dt.Columns
If dc.DataType.FullName = GetType(DateTime).FullName Then
If dr(dc) = Date.MinValue Then
drtmp(dc.ColumnName) = SqlTypes.SqlDateTime.Null
Else
drtmp(dc.ColumnName) = dr(dc)
End If
Else
drtmp(dc.ColumnName) = dr(dc)
End If
Next
dtOut.Rows.Add(drtmp)
Next
dtOut.EndLoadData()
public void ChangeDateTimeColumn(DataTable newDataTable)
{
for (int i = 0; i < newDataTable.Rows.Count; i++)
{
for (int j = 0; j < newDataTable.Columns.Count; j++)
{
DataColumn dc = newDataTable.Columns[j];
if (dc.DataType == typeof(DateTime))
{
string name = dc.ColumnName;
DataRow row = newDataTable.Rows[i];
if (row[name] != null && row[name].ToString().Trim() != "")
{
DateTime value = (DateTime)row[name];
if (value < (DateTime)SqlDateTime.MinValue)
{
row[name] = (DateTime)SqlDateTime.MinValue;
}
else if ((DateTime)SqlDateTime.MaxValue < value)
{
row[name] = (DateTime)SqlDateTime.MaxValue;
}
}
}
}
}
}
精彩评论