Datetime interpretation issue - sql

I have the following data:
StartDate FinishDate Details
09/10/2013 11/10/2013 xxx
14/10/2013 13/10/2014 Taking a year off
Whilst editing this data I which to check the date ranges do not overlap.
I am running an SQL query from access via ado to do this; I am putting the dates entered into database format (ie 'mm/dd/yyyy'); This is the query I've got:
SELECT Count(*)
FROM MarkerAbsence
WHERE PerID = 718 AND
('10/09/2013' BETWEEN StartDate AND FinishDate OR
'10/11/2013' BETWEEN StartDate AND FinishDate)
If the data is valid, it should return zero records; however it doesnt it returns 1 (being the second listed record above) and therefore seems to be interpreting '10/11/2013' as dd/mm/yyyy instead of mm/dd/yyyy.
Yet if I do this in SMO:
DECLARE #datevar datetime2 = '31/12/2008';
SELECT #datevar;
I get:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
While
DECLARE #datevar datetime2 = '12/31/2008';
SELECT #datevar;
returns
2008-12-31 00:00:00.0000000
So why am I having this problem and how do I fix it?

If you're running a query using MS Access, you need to delimit dates with # symbols, i.e.: #12/31/2008#. If this won't work for whatever reason, it is best to use string dates in the 'yyyy-mm-dd' format, as it will be recognized and is unambiguous.
You're probably getting this problem as MS is a US company, and the US uses mm/dd/yyyy format, so MS has defaulted much of their older software to treat dates as being in this format if at all possible, whereas you're probably in a country that uses - and have your PC's locality set to use - dd/mm/yyy format. Since not all of MS' software follows this rule, you have this problem.
The solution is to use a string date format that is unambiguous, such as: yyyy-mm-dd, mmm/dd/yyyy, or dd/mmm/yyyy (where mmm returns a three-letter month such as Dec).

You are using dd/mm/yyyy formats for your date strings. By default, without an explicit conversion, SQL is expecting date strings in the mm/dd/yyyy or yyyy-mm-dd format. So either change your strings to match one of these formats or do this:
SELECT Count(*)
FROM MarkerAbsence
WHERE PerID = 718 AND
(CONVERT(DATETIME, '10/09/2013', 103) BETWEEN StartDate AND FinishDate OR
CONVERT(DATETIME, '10/11/2013', 103) BETWEEN StartDate AND FinishDate)

Related

SQL Server clean up inconsistent dates

I have dates currently stored as varchar(1000) that are in inconsistent formats. I.e. yyyy-mm-dd and dd-mm-yyyy etc.
What query can I run to clean these up so they are in a consistent format, so I can convert the column datatype from varchar(1000) to date?
Thanks
This could get ugly if you have many different date formats, possibly including invalid data. One option would be to assign a new date column using a CASE expression to choose the correct format mask:
UPDATE yourTable
SET date_col = CASE WHEN date LIKE '[0-9]{2}-[0-9]{2}-[0-9]{4}'
THEN CONVERT(datetime, date, 105)
WHEN date LIKE '[0-9]{4}-[0-9]{2}-[0-9]{2}'
THEN CONVERT(datetime, date) END;
You may add conditions to the above CASE expression for other date formats.

SQL Server date conversion not is formatting the output

My SQL statement is supposed to add 5 days to the date column and reformat the output to MM/DD/YYYY.
The calculation is working, but the format won't change, no matter what value I use.
The date column is defined as varchar(128) (I've used datetime and varchar(128) in the convert statement).
What am I doing wrong?
SELECT
FSI_Date, DATEADD("d", +5, CONVERT(DATE, FSI_Date, 101)) AS NEWDAY,
FROM
DB_test
FSI_Date NEWDAY
---------------------------
12/12/2015 2015-12-17
SQL Server will convert mm/dd/yyyy to a date, so, you just need the dateadd() and then convert back to your desired format.
Remove the final convert(...,101) if you want a natural date.
Example
Select FSI_Date
,NewDay = convert(varchar(10),DateAdd(DAY,5,#FSI_Date),101)
From DB_Test
Returns
FSI_Date NewDay
12/12/2015 12/17/2015

SQL - Convert String to Date and compare - Conversion failed when converting datetime from character string

I currently have dates stored in a general attribute field in the database as a string.
They are all stored in the format DD/MM/YYYY for example 01/01/2000
I am able to convert them them to datetime successfully by using the following in my select statement. For example CONVERT(DATETIME, attribute.field_value, 103) where attribute.field_value contains a date.
The SELECT statement works fine and returns the whole table with them correctly.
I can also return a column with todays date in the same format as follows CAST(getdate() AS datetime)
The problem occurs when I try to compare, now I only want to return everything that is newer than today in pseudo code that would dateNewerThanToday > dateToday
Therefore I have tried
WHERE CONVERT(DATETIME, attribute.field_value, 103) > CAST(getdate() AS datetime)
this gives me the error
Conversion failed when converting datetime from character string.
I have tried a multitude of cast/converts to get it to work. I have also wrapped by select so I am only doing it on dataset with the correct data.
Any help would be super useful! Many thanks in advance!!
A couple of things ..
You do not need to convert to GETDATE() to DATETIME data type as it already returns datetime data type.
Instead of CONVERT(DATETIME, attribute.field_value, 103)
use
CONVERT(DATETIME, attribute.field_value) or CAST(attribute.field_value AS DATETIME)
Add a where clause in your select to get only valid DATETIME values. something like
WHERE ISDATE(attribute.field_value) = 1
This will filter out any values which appears to be a date value but sql server doesnt see them as valid date values.
Important Not
Use appropriate data types. If this column is storing date values why not use the DATE or DATETIME data types.
I ran into this exact problem.
Values from a VARCHAR(50) column returned in the SELECT could be cast as date without issue. However when cast in a comparison in the WHERE clause the error occurred.
Of note, the error only occurred when I had other restrictions in the WHERE clause.
When I added ISDATE() to the WHERE clause, the error no longer occurred.
e.g. Shortened example of what worked:
SELECT CONVERT(DATE, mat.myAttributeColumn), mdct.myDateComparisonColumn
FROM myAttributeTable mat
JOIN myDateComparisonTable mdct ON mdct.key = mat.key
WHERE ISDATE(mat.myAttributeColumn) = 1
and mdct.myDateComparisonColumn < convert(DATE, mat.myAttributeColumn)

query on date column

I have a column (completeddate) that I need to do the following
select *
from orders
where completeddate > '01-01-2013'
The problem is the date in the field looks like this (below)
25-FEB-08 12.00.00.000000000 AM
The format of the column is this
TIMESTAMP(6)
How do I set up my query to return rows where the completeddate is greater than 01-01-2013
Try this
select *
from orders
where completeddate > CONVERT(DATETIME, '01-01-2013', 105)
105 for dd-MM-yyy
You haven't specified the DBMS you are using, but nearly all of them store dates as a number. The format that you are seeing is almost certainly the client's interpretation of the date and has nothing to do with how the date is actually stored.
Most DBMSes are able to translate standard string representations of dates into a numeric date value. The likely problem is that you aren't using a standard date format. You should either use '2013-01-01' or '01/01/2013'. In my experience, YYYY-MM-DD (ISO 8601 and RFC 3339) is the least ambiguious and most supported format. If you strongly prefer MM/DD/YYYY (a primarily North American representation) then you usually need to use backslashes.
You need to convert the string '01-01-2013' to a database date object before the comparison. Don't know what is the type of your database, but all databases shall provide a function for converting date objects to and from strings, you can have something like:
where completeddate > TO_DATE('01-01-2013', 'DD-MM-YYYY')
Hope this helps.
did you try this?
SELECT CAST(your_timestamp_field AS DATETIME) FROM orders WHERE completeddate > '2013-01-01'

Formatting Dates In SqlServer To Use As Comparison

This should be easy
I have a date column on table A
SELECT * FROM TABLEA
WHERE DTE = '01/02/2010'
The problem is that this is deployed onto US servers and I have no control over the date as its an arg.
How can I tell SqlServer to treat this date as being in that format??
I gave tried this:
SELECT *
FROM TABLEA
WHERE DTE = CONVERT(VARCHAR(10), '01/01/2010' , 101) AS [DD/MM/YYYY]
Your last try was almost correct, but it should have been
SELECT * FROM TABLEA WHERE AS_OF_DATE = CONVERT(DATETIME, '01/01/2010', 101)
Use a safe format. For dates (without a time component), the safe format is YYYYMMDD, e.g. today is '20100209'.
For datetimes, the safe format is YYYY-MM-DD'T'HH:mm:SS, where 'T' is the literal T, so right now is '2010-02-09T11:10:30'.
(When I'm saying safe, I mean that SQL Server always, unambiguously, knows how to convert these strings into datetime values)
Check out this reference article: The ultimate guide to the datetime datatypes
EDIT: Specifically what Tibor says about SET DATEFORMAT & SET LANGUAGE, since you mention that you have no control over the input format.
Another option is a double conversion (check performance when used as criteria):
select strTempNo, dtmTempDateStart,
convert(varchar(10), Convert(datetime, dtmTempDateStart, 103), 126) As UTCDate
I use 103 here as the data is already in UTC format but this works as well (UTC ISO8601 is 126).
If your dates are known to be always in American format you have to use 101.
Alternatively use 112 (ISO "safe" format) and cut the first 8 characters out of the string.
Data sample: (Sorry, don't have an American date table available)
521002 2008-09-1500:00:00.000 2008-09-15
580195 2008-04-1500:00:00.000 2008-04-15
530058 2008-09-2200:00:00.000 2008-09-22
580194 2008-04-0200:00:00.000 2008-04-02
500897 2008-07-0100:00:00.000 2008-07-01
500966 2008-09-2300:00:00.000 2008-09-23