views:

265

answers:

2

Hi, I am trying do a database update via stored procedure using ADO.NET.

Basically i setup all the parameter and command and have the one of the parameter set like the following

DbParameter nm8 = provider.CreateParameter();
nm8.ParameterName = "@EDITDATE";
nm8.DbType = System.Data.DbType.DateTime;
nm8.Value = aObject.ADateTime;
command.Parameters.Add(nm8);

In the stored procedure, the input parameter is defined as

@EDITDATE       datetime = null,

and basically what the stored proc does is just get a record and update it with the EDITDATE passed in.

but i am getting this error

Error converting data type varchar to datetime.

and what i found was that the datetime value is passed in to the stored procedure as something like the following

2010-02-03 15:26:54.3100000

instead of

2010-02-03 15:26:54.310

and i think that's what is causing the casting error.

so my question is why ado.net convert the datetime in that format? how can I resolve the issue without passing the value in as string.

thanks a lot.

A: 

Certainly this throws an error in SQL Server 2005:

print cast('2010-02-03 15:26:54.3100000' as datetime)

whereas this works fine:

print cast('2010-02-03 15:26:54.31' as datetime)

But ... is aObject.ADateTime not of type DateTime? It sounds like it's being passed to the stored procedure as a string.

If it is indeed a string, I would suggest converting it to DateTime before you pass it in:

nm8.Value = DateTime.Parse(aObject.ADateTime);
Matt Hamilton
thanks for the reply, ADateTime is indeed of type DateTime.That's what I don't understand, the DbType is set to DateTime and the value passed in is a DateTime object as well (DateTime? to be precise)Isn't that all i need to do? for a datetime parameter in a stored procedure?
Eatdoku
@Eatdoku That's definitely very strange. I've never had any problems passing a DateTime to a stored proc like that. How much precision do you need? Could you round the DateTime to the nearest second?
Matt Hamilton
Nearest second would be more than enough in my case.But i think the problem is how ado.net translate the DateTime into string when passing down to the stored proc.My solution for now is to pass down DateTime.Tostring(format) directly as DbType.String and it worked fine.still interested in knowing how ado.net converts the datetime and why am I seeing this weird result.thanks
Eatdoku
A: 

Do you have to program against the base class or can you use SqlParameter? (assuming you are using connecting to Sql Server) Maybe you can try setting the SqlDbType property

SqlParameter sqlParam = (SqlParameter)nm8; //check if it's compatible before casting.
sqlParam.SqlDbType = SqlDbType.DateTime
alwayslearning
good point, I am working with SQL Server. But instead of SqlDatProvider I use DbProvider. Maybe that's why the converted DataTime string is a bit different than what SQL Server is expecting.
Eatdoku