开发者

Get SqlDateTime overflow in SqlBulkCopy.WriteToServer()

I insert data from a typed dataset into my MSSQL database by using SqlBuldCopy class:

foreach (DataTable dt in ds.Tables)
{
    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn)) 
    {
        bulkCopy.DestinationTableName = "dbo." + dt.TableName + "_neu";

        try
        {
            bulkCopy.WriteToServer(dt);
        }
        catch (Exception ex)
        {
            throw new FaultException("\n" + dt.TableName + ": " + ex.Message);
        }
    }
}

It works great. But when I insert DataTime.MinValue into my database i get this error: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM. Is there a way to say in the foreach something like this: if DateTime field value from dataset is DateTime.MinValue, don't开发者_运维技巧 insert the DateTime field from dataset into my database?

Best regards


I think you'd need to ensure there are no DateTime.MinValue's in the datatable - do you control the population of that table?

If so, instead of storing DateTime.MinValue in a DateTime field, use SqlDateTime.MinValue instead. Or, store DBNull in the datatable instead if you want NULL to be stored in to the DB.


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;
                    }
                }
            }
        }
    }
} 


If you've got SQL Server 2008 and don't mind storing the MinValue you can get round this by using DateTime2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜