I have an NVARCHAR column named Receivingdate. I want to compare its content with the current time, but when I call WHERE (Receivingdate < Getdate()), I get the following error:
The conversion of nvarchar to datetime resulted in an out of range value
I insert the data using the following call from C#:
DateTime.Now.AddDays(ces).ToString("dd/MM/yyyy");
I'm wondering what I'm doing wrong.
What you're doing wrong is storing dates in an NVARCHAR column. Please stop doing that. Fix your table and make that column using the DATE data type. The error is caused by garbage data getting into your table. Find those rows using:
SELECT Receivingdate FROM dbo.YourTable
WHERE ISDATE(ReceivingDate) = 0;
Now, you'll need to either correct or get rid of those before you fix the data type. Then:
ALTER TABLE dbo.YourTable
ALTER COLUMN ReceivingDate DATE;
Next, stop converting to a regional string format when inserting. Just insert the DateTime value from C# without calling .ToString() at all. There is absolutely no reason you should ever be converting to date to string and back again through any of this process, except at the point where you want to display it.
Your error is that you are trying to compare a string to a date. Dates are numbers. The only time to worry about format is when you are displaying them.
For what you have shown so far, change your c# code from
DateTime.Now.AddDays(ces).ToString("dd/MM/yyyy");
to
DateTime.Today;
and you should be ok.
Related
I extracted tweets from twitter streaming api and stored all the Timestamp (of tweets) in the MySQL varchar field. Now, I would want to extract all the tweets for the last one hour. Is it possible to query the database and fetch the results accordingly?
I extracted around 500,000+ tweets and I am not sure if I would be able to change the type of the field and still safeguard all the values.
Time format which I saved in varchar field: 'Wed Oct 10 16:29:56 +0000 2012'
You could use the STR_TO_DATE function as you select the rows to convert the date column into something you can compare. But if you are keeping this data for the long term, you should convert the type of the column to datetime, which would entail moving the data to another table.
You can try str_to_date for your select criteria.
You should convert that field to DATETIME though. Even if str_to_date works the performance is going to be horrifying. :)
I want to insert current date into a database in the field cur_dt having datatype date.
string curr_dat= DateTime.Now.ToString("yyyy-mm-dd");
Can i insert curr_dat which is a string variable into a column cur_dt having datatype as date?
If not than how can i do it? How to define a date variable.I want to also insert current time in the a column cur_tm having datatype time.
Please help me to understand how to insert the date and time into the database.
If you write SQL like
INSERT INTO foo SET bar='<date here>'
or similar, you can use both parameters or just String.Format to put the date there as a STring.
Additionally, if you want to put the current Date/Time there, why not just use
INSERT INTO foo SET bar=now() -- if column type is datetime
INSERT INTO foo SET bar=CURDATE() -- if column type is date
and have the database set in the correct date in the correct form
read mysql date/time functions here http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
You would need to convert curr_dat variable to DateTime before assigning it to cur_dt column. You can also create a new DateTime value is following way
DateTime curDate = new DateTime(DateTime.Now.Year,DateTime.Now.Month, DateTime.Now.Day,0,0,0);
and assign the value to cur_dt column.
str_to_date(string_data, format)
STR_TO_DATE('Dec/15/2011', '%M/%d/%Y'); => 2011-12-15
I need to sort by date but the date is stored as text in the database. I am using Linq to entities to perform queries.
The way the database is designed it is not feasible to change the column to a date column because many different data types are in that column. There is a descriminator column named type so I will know what type a particular row is.
You can add a computed column to the table that will convert those strings to dates when your discriminator has a specific value (here I've just used 'date').
ALTER TABLE Foo
ADD trueDate AS
CASE
WHEN type = 'date' THEN CONVERT(date, 'mixedColumn', 101)
ELSE NULL
END
PERSISTED
If you have time information, then date should be datetime in the CONVERT() function.
Also, the 101 is a style code indicating an expected format of MM/dd/yyyy. If you have something different, refer to this: http://msdn.microsoft.com/en-us/library/ms187928.aspx, but keep in mind that if you use a style below 100 your expression will be considered non-deterministic and you cannot make your computed column PERSISTED, so the conversions will be done on the fly with each query (you don't want that).
The computed column will update itself when the row values change; otherwise the values are persisted and queryable just like in any other column. No triggers required.
If all your rows containing dates use the same date format you could just order by their string value. But since the most common (i.e english) date format does NOT start with the year, that could prove problematic.
Option A.: Sort in memory.
var records = db.YourTable.Where(o=>o.Discriminator =="date").AsEnumerable()
.Select(o=>new {Entity= o, Date=DateTime.Parse(o.YourColumn)})
.OrderBy(o.Date).Select(o=>o.Entity);
Do NOT do this if you have a lot of rows, or if you have to, at least have the decency to cache the ordered result...
Option B.: Database magic
Add an extra column to your DB, make THAT Date (nullable), and update that if the discriminator is date. You can either update it in a (DML) Trigger or from C#...
OR if the conversion is simple you could build a view out of it...
I have a Db server with DateTime fields in the format of "yyyy-MM-dd mm:hh:ss"
I'm trying to use linq2sql to insert a DateTime member to a DateTime field in one of my tables.
When I do it in SQL I convert the DateTime as following:
"Insert into .... Convert(datetime, getdate(), 120) ..."
But when I try to submit the object from Linq the date time inserts in the wrong format.
Is there a way to define the format that will be inserted to the Db in Linq?
Or is it a DateTime object Issue?
You shouldn't be dealing with a string format when you pass dates and times to the database, any more than you would if you were passing a number. The database should be handling all this for you without any conversions. This is true whether you're using LINQ or within the SQL - almost any time you have to manually do string conversions between types at the database level, you should look for a better solution.
If you read the value back out of the database (as a DateTime again) does it have the right value? If not, in what way is it wrong?
I am working with C#.net and also SQL Server 2008.
I have the following error, when trying to run a test unit within my project.
System.Data.SqlTypes.SqlTypeException:
SqlDateTime overflow. Must be between
1/1/1753 12:00:00 AM and 12/31/9999
11:59:59 PM..
Database Table
Column Name: createddate
Type: datetime
Default Value: (getdate())
Allow Nulls: No.
I don't want to insert the createddate as part of my INSERT query.
When I manually enter some data into the database table I get the following error:
The row was successfully committed
to the database. However, a problem
occurred when attempting to retrieve
the data back after commit. Because
of this the displayed data within the
row is read-only. To fix this
problem, please re-run the query.
I don’t understand why I am getting this error and cannot find anyone who has had this problem. Can anyone help?
Matt is most likely on the right track. You have defined a default value for your column - however, that will only take effect if you actually insert something in your table in the database.
When you do a unit test, as you say, you most likely initialize the DateTime variable to something (or not - then it'll be DateTime.MinValue, which is 01/01/0001) and then you send that to the SQL Server and this value is outside the valid range for a DATETIME on SQL Server (as the error clearly states).
So what you need to do is add a line to your .NET unit test to initialize the DateTime variable to "DateTime.Today":
DateTime myDateTime = DateTime.Today
and then insert that into SQL Server.
OR: you can change your SQL INSERT statement so that it does not insert a value for that column - it looks like right now, it does do that (and attempts to insert that - for SQL Server - invalid date into the table). If you don't specify that column in your INSERT, then the column default of getdate() will kick in and insert today's date into the column.
Marc
Are you using Linq to SQL to write your unit test?
If you are, it might be bypassing the getdate() default value, and using some other value instead which falls outside the valid range.
I got the same issue, I was using Linq with the DataClasses files automatically generated by VS2010.
The I realised that Linq is not using the default value (GetDate()) but it will send a Datetime.Min value. As the consequence the SQL server will reject this datetime "01/01/0001" because it's not in range.
What I did to fix it is to always set the value to Datetime.Now or Datetime.Today and so Linq will not send the bad Min Datetime value anymore.
You are probably getting an overflow error in your unit test because you are passing in an uninitialised DateTime with the value DateTime.MinValue which is outside the allowable range for SQL's datetime.
I think I have seen that error message when modifying the table manually, it isn't a problem, just refresh the table.
are you using a data context class setup with the DBML file and all that jazz? If so, then you can click on the field in your DBML file and set the "Auto Generated Value property" to True. Visual Studio must already know to do this with the Pkey fields, but has to be set for these "timestamping" sort of actions