views:

25

answers:

2

Hi,

I'm trying to do the following:

using (var tx = sqlConnection.BeginTransaction())
{
 var command = sqlConnection.CreateCommand();
 command.Transaction = tx;
 command.CommandText = "INSERT INTO TryDate([MyDate]) VALUES(@p0)";
 var dateParam = command.CreateParameter();
 dateParam.ParameterName = "@p0";
 dateParam.DbType = DbType.Date;
 dateParam.Value = DateTime.MinValue.Date;
 command.Parameters.Add(dateParam);
 command.ExecuteNonQuery();
 tx.Commit();
}

where the table has a SQL Server 2008 Date column. I can insert a value of '01/01/0001' into this via SQL Management Studio.

If I run the above on the ExecuteNonQuery I get a "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM." exception.

Why is this? The SQL Server Date field does indeed accept 01/01/0001.

+1  A: 

This works...

var command = sqlConnection.CreateCommand();
command.Transaction = tx;
command.CommandText = "INSERT INTO TryDate([MyDate]) VALUES(@p0)";
SqlParameter dateParam = new SqlParameter();
dateParam.ParameterName = "@p0";
dateParam.SqlDbType = SqlDbType.Date;
dateParam.Value = DateTime.MinValue.Date;
command.Parameters.Add(dateParam);
command.ExecuteNonQuery();
Will A
Reflecting the SqlParameter code shows that there's a definite distinction between DbType.Date and SqlDbType.Date - I've not found the particular line of code in the Framework that results in the error - however, using SqlDbType.Date should definitely solve this.
Will A
Thanks Will A. I suspected this would be the answer but really don't get why the "generic" DbType Date would fail with a SQL Server error. Especially since there is a also a DateTime DbType that I'd expect to match up to the original SQL DateTime type that have always had this restriction.Looks like a .NET bug to me.
Graham
A: 

As the error says Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

SQLServer DateTime columns have different min and max values than a dateTime variable in the CLR.

You may want to put logic in your program to protect the database from datetimes that are out of the SQLServer range.

automatic
I initially thought this was it to, but he's using the newer `DATE` datatype. `DATE` and `DATETIME2` match the range of values allowed by the CLR. His problem appears to be in the ADO.NET call, not in SQL Server. His code must be inferring `DATETIME` instead of `DATE` somewhere.
mattmc3
Nope - using DbType.Date rather than SqlDbType.Date is breaking the code and restricting the range.
Will A