ADO.NET Update command with datetime parameter issue - datetime

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.

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

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

Related

CLR DateTime object comparison with SQL Server DateTime

I'm using this implementation to conduct server side searching using Entity Framework for jqGrid. The issue that I'm having is that although the search is working fine for text or numerical fields, searching using DateTime values isn't working.
The problem is that the DateTime object in my model class sends the string representation of the object (i.e. in the format 2/9/2014 12:00:00 AM) to the database but the database is formatted as 2014-09-03 00:00:00:000. As a result, the comparison always fails.
I can't change my DateTime property to a string so I'm stumped. The resultset is returned via a stored procedure (a simple SELECT * FROM [TableName]) so I tried formatting the associated Date field and returning that but it returns as an nvarchar.
Has anyone encountered this before or have any recommendations as to how to resolve this issue? I'd appreciate any help, thanks!
Just to provide an answer for anyone who comes across this. I took the following steps to resolve this issue:
1) Made the following change in the JQGrid support class:
_formatObjects.Add(parseMethod.Invoke(props[rule.field], new object[] { rule.data }));
to
_formatObjects.Add(parseMethod.Invoke(props[rule.field], new object[] { (parseMethod.ReturnType.FullName == "System.DateTime" && rule.data != "") ? Convert.ToDateTime(rule.data, CultureInfo.CreateSpecificCulture("fr-FR")).ToString() : rule.data }));
2a) In my controller, I added the following bit of code whenever I was fetching directly from the table (you have to specify the column names explicitly to truncate the time portion):
//For matching date instead of datetime values
if (wc.Clause.Contains("Date"))
{
wc.Clause = wc.Clause.Replace("DeliveryDate", "DbFunctions.TruncateTime(DeliveryDate)");
}
results = results.Where(wc.Clause, wc.FormatObjects);
2b) If the data was being returned from a stored procedure, I just returned an appropriate Date field from the SP (this approach will work for DateTime fields only if the timestamp portion is all zeros).
Hope this helps someone else.

ASP.NET saving empty date value in SQL Server database with parameters

I have a web forms application which allows to update database columns. One of the database columns is Finish Date which is of date datatype in the SQL Server database.
I use SQL query with parameters and textbox to provide the new value for the finish date.
This is a code which gets me the value of the date from a text box within the grid:
TextBox tFD = (TextBox)grdProjectUpdate.Rows[e.RowIndex].Cells[11].FindControl("proFDTextBox");
then I use a parameter:
cmd.Parameters.Add("#proFD", SqlDbType.Date).Value = tFD.Text.Trim();
to update the value using this SQL statement:
UPDATE PMSprojects SET proFD = #proFD ,...
This solution works fine whenever there is an actual date provided. However, it does not save nulls. If I provide an empty string, it is being converted into 1900-01-01 date, even though the column in the database allows nulls.
How could I solve this issue and save null to the database?
You have to write code around this to handle, and pass DbNull.Value when the value is null.
cmd.Parameters.Add("#proFD", SqlDbType.Date).Value = (tFD.Text.Trim().Length > 0) ? (object)tFD.Text.Trim() : DbNull.Value;

JPA and SQLite3 - Wrong date

A date field in my entity class is defined as below:
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_EXECUTED")
private Date lastExecuted = new Date();
However, when it is persisted to a SQLite3 database through JPA, the database value is always '1899-12-30'. Do you have any ideas why?
In the database, the field is defined as DATETIME.
I've tried using both SqliteJDBC and Xerial SQLite JDBC.
Update: After turning on SQL debugging in EclipseLink JPA, and turning off parameter binding, it looks like dates are inserted as following:
insert into run (last_executed) values ('{ts ''2012-02-17 10:34:58.013''}');
which, if inserted, manually in SQLite, gives the date '1899-12-30'.
Of course, any workarounds would be greatly appreciated.
The date looks correct in the insert, so seems to be some kind of SQLite issue. You should normally use parameter binding, it seems SQLite does allow Timestamp to be bound, or ignores the DATE portion. What if you use TemporalType.DATE?
Perhaps try through raw JDBC to see exactly what your JDBC drivers issue are?
For the printed syntax if not using parameter binding, you can customize this by creating your own DatabasePlatform subclass. The syntax you printed is the standard JDBC timestamp syntax.
Can you verify that it is a java.util.Date and not a java.sql.Date?
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_EXECUTED")
private java.util.Date lastExecuted = new Date();
What does the debug output look like if you turn parameter binding back on?
Use smalldatetime solve the problem~~~ Try it.

Inserting DateTime values into database?

This seems like it should be really obvious, but how can I put a DateTime object into an MSSQL database? When I convert it to a string, it keeps adding "-7:00" at the end for the time zone offset and so the query isn't accepted. How can I fix this?
How are you trying to insert the DateTime into the database? If you're converting it to a string to be passed into a stored procedure (bad idea; better to use the date SQL type), then you should first convert all DateTime objects to UTC using the .net method ToUniversalTime. Once in UTC, the DateTime will have no timezone offset.
Assuming you are using C#, I would suggest the following:
SqlCommand cmd = new SqlCommand("INSERT INTO yourTable (dateTimeColumn) VALUES (#value)", connection);
cmd.Parameters.AddWithValue("#value", yourDateTimeObject);
cmd.ExecuteNonQuery();
This will work for inserting the value. If not, please post your code to show where the error is because that means that the datetime object you are getting your value from is passing in the data wrong.

Date Time format problem in sql server

I have an application in asp.net which worked fine untill recently when i changed the datetime format in Regional and Language Settings in Control Panel.
The date time format was default when i installed XP. I chose Indian standard time while installing XP.
I changed the date time format to dd/MM/yyyy HH:mm:ss. And my application started to throw an exception whenever i tried to insert any datetime in to the table.
The exception i get is:
System.Data.SqlClient.SqlException: Error converting data type varchar to datetime.
Please help me on this
Hard to know exactly what's going on without seeing the code that's throwing. However, if you need to communicate dates to SQL Server, it is generally good practice to use the ISO 8601 standard for representation because it is unambiguous and locale-independent. The most important formats are:
yyyy-MM-dd for dates
hh:mm:ss for time
yyyy-MM-dd hh:mm:ss for date/time
My guess is that you have a query that's sending over dates in the current locale, and the locale on the server does not match.
Edit: And for the record, this doesn't preclude anything that Rob said in his answer, i.e. try to avoid passing hard-coded dates or hard-coded SQL at all. This only applies if you need to for some reason.
Edit 2: I've been informed that the yyyy-MM-dd format can still be wrong for some locales; so instead of this, if you need to pass in a literal date string, you should instead use yyyyMMdd.
As per my comment, you'll probably want to make sure you're using code that behaves in a similar way to the code below (i.e. using parameters rather than string concatenation)
var myConnectionString = "connection string goes here";
var myDateValue = DateTime.Now;
using (var connection = new SqlConnection(myConnectionString))
{
using (var command = new SqlCommand("SELECT COUNT(1) FROM dbo.table WHERE datecolumn = #datevalue", connection))
{
var dateValueParameter = new SqlParameter("#datevalue", myDateValue);
command.Parameters.Add(dateValueParameter);
var result = Convert.ToInt32(command.ExecuteScalar());
}
}
Try adding "Current Language=YourLanguage" to the SQL server connection string. Where YourLanguage is the language you want SQL to use when reading values such as the dates.
You can see a list of all languages supported by SQL by executing the following SQL command:
select * from master.dbo.syslanguages

Resources