Error comparing dates in SQL query - sql

Within a ASP.NET/C# class I am trying to run a query where I compare dates:
select * from table1 CreatedDate >='DATEADD(d,-500,GETDATE())';
Basically I am trying to select rows from the the last 500 days.
The problem is I am getting the following error:
Syntax error converting datetime from character string.
An example of the CreatedDate field in the database is 2003-09-19 15:32:23.283 . The field is set to type = datetime, default = getdate().
If I run the query SELECT DATEADD(d,-500,GETDATE()); it returns 2008-09-17 23:41:34.710
The 2 values look the same so I am surprised am getting the error message. An idea on how I need to modify my query?

select * from table1 CreatedDate >= DATEADD(d,-500,GETDATE())
Lose the quotes around DATEADD(d,-500,GETDATE()). These make the expression varchar
Datatype precedence means you are trying to convert a string starting DATEADD to datetime...

have you tried without the single quotes?
CreatedDate >=DATEADD(d,-500,GETDATE())

You have put apostrophes around the dateadd expression, so it's not an expression, it's a string. That's the string that it fails to convert to a datetime value.
select * from table1 CreatedDate >= DATEADD(d,-500,GETDATE());

just remove '' quotes

Related

MM/dd/yyyy datetime data type resulted in an out-of-range value

I am inputting 2 date values in order to filter out from SQL query.
EXEC [Report].[usp_EmployeeReport_Detail] '01-01-2017','31-08-2019'
I am inputting the date as MM/dd/yyyy and the
WHERE clause contains
(j.StartDate BETWEEN #BegDate AND #EndDate)
I m getting the below error when executing the query.
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
I tried to convert the datetime result using the below way as well.
SELECT CONVERT(datetime,01-31-2017,101)
This returns 1894-05-25 00:00:00.000 as the response. How its possible?
As #Damien_The_Unbeliever has said,01-31-2017 using the Numerical expression, which evaluates to -2047.
-2047 means the day minus 2047 days from 1900-01-01, so result of date will be 1894-05-25 00:00:00.000.
So your query SELECT CONVERT(datetime,01-31-2017,101) same as SELECT CONVERT(datetime,-2047,101)
sqlfiddle
You can use the ANSI compliant format YYYYMMDD
SELECT CONVERT(datetime,'20170131',101);
instead of
DD-MM-YYYY 01-31-2017.
Or just add ' to contain the date '01-31-2017' like #fa06 answered.
Try this: u've missed the quote in date:
SELECT CONVERT(datetime,'01-31-2017',101)
try below way
SELECT CONVERT(CHAR,GETDATE(),1 )
it returns 08/13/18
in your case you missed the quote as a result output that type shown

Convert from varchar into date in SQL Server

This looks easy solution but I can't seem to figure out as to why this is not working for me. I have a column that has data like this:
DateField
----------
12/16/2016
11/06/2016
All I want to do is to convert from varchar into a date column, but I am getting this error:
Conversion failed when converting date and/or time from character string.
Here is my simple query:
select convert (date, DateField) as convertedField
from myTable
Nothing wrong with the two examples you have given. There are some bad dates in your table which cannot be converted to date.
Use TRY_CONVERT function for bad dates it will return NULL
select TRY_Convert(date,DateField)
From myTable
You should always store dates in DATE/DATETIME datatype.
If you want to see the records which cannot be converted to date then
select DateField
From myTable
Where TRY_Convert(date,DateField) IS NULL
If working with a specific date format like mm/dd/yyyy You can specify it in Convert() function like the following
CONVERT(DATETIME,DATAFIELD,101)
If it still is not working, use TRY_CONVERT() to get which rows are throwing this exception:
SELECT *
FROM TBL
WHERE TRY_CONVERT(DATETIME, DATAFIELD, 101) IS NULL
This will return rows that cannot be converted
TRY_CONVERT() will return NULL if conversion failed
Read more about DateTime formats here:
SQL Server CONVERT() Function tutorial
Read TRY_CONVERT MSDN Article
You need to specify the format of date time while formatting. The date in your table is currently in U.S format so you should pass the third argument 101 in your convert function.
SELECT CONVERT(date,[DateField],101) FROM myTable;
Working Fiddle here http://rextester.com/NYKR49788
More info about date time style here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

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)

SQL datetime LIKE select - why do I need an extra %?

Can someone explain to me why when I perform a LIKE select in SQL (T-SQL) on a varchar column I can do the following:
SELECT *
FROM Table
WHERE Name LIKE 'Th%'
to get names beginning with Th, but when I do the same on a datetime column I need a % before the year, like:
SELECT *
FROM Table
WHERE Date LIKE '%2013%'
to get dates in 2013. The datetimes are stored in yyyy-MM-dd hh:mm:ss format. I know I could use a DATEPART style query but I was just interested in why I need the extra % here.
The DATETIME is converted to a VARCHAR before the comparison, and there definitely is no guarantee that the conversion will be in the pattern you mention. DATETIME is not stored internally as a VARCHAR but as a FLOAT.
You should stop wondering because the syntax is not useful.
SELECT *
FROM Table
WHERE Date LIKE '%2013%'
Will give you a full table scan because the date will be converted to a varchar when comparing. In other words, don't do it !
Use this syntax instead:
SELECT *
FROM Table
WHERE Date >= '2013-01-01T00:00:00'
and Date < '2014-01-01T00:00:00'
If the Date field is in timestamp:-
SELECT *
FROM Table
WHERE year(Date) = '2013'
The sql server converts datetime to this format (Jan 1, 1900 9:20AM.)Because of that reason We need to use an extra %.
If you want to search the records start with month Jan
you can use following query for date time
SELECT *
FROM Table
WHERE Date LIKE 'Jan%'.
No need of extra '%'.

Convert NVARCHAR to DATETIME and select distinct Year

SELECT DISTINCT YEAR(convert(varchar(max),OrderCreatedDate)) from webshop
The above sql query is producing this error:
Conversion failed when converting date and/or time from character string.
The value in the database is NVARCHAR and in the following format: DD/MM/YYYY 00:00:00 AM (/PM)
I would like to select the unique values for the year only!
thanks for any help
To avoid this sort of issues, date should be saved in DateTime type field Not in a string field.
Year() function parameter is a DateTime type not a String. So you should make sure that the string you are passing is convertible to a DateTime type. In this case you could trim out the time part with Left() function and use 103 style as below.
Fiddle demo:
--Example
declare #val nvarchar(50) = '28/10/2013 11:25:45 AM (/PM)'
select year(convert(date,left(#val,10),103)) myYear
--Applying to your query
SELECT DISTINCT Year(Convert(Date,Left(OrderCreatedDate,10),103)) FROM Webshop
UPDATE:
If you are getting errors, it could be due to your date format. i.e. Format of the string you have saved may not be as you have described (DD/MM/YYYY 00:00:00 AM (/PM)) in the question.
Please check with ISDATE() function before converting to date and identify which records are causing the problem and correct them.
Try this query to get all of them with invalid strings. Following query will return 0 for values with invalid formatting.
SELECT DISTINCT CASE WHEN IsDate(eft(OrderCreatedDate,10))=1 THEN
Year(Convert(Date,Left(OrderCreatedDate,10),103))
ELSE 0 END as myDate,
OrderCreatedDate
FROM Webshop
Or you could get only the records which are causing the problem as;
SELECT OrderCreatedDate
FROM Webshop
WHERE IsDate(Left(OrderCreatedDate,10)) = 0
select distinct year(CONVERT(NVARCHAR(255),CONVERT(SMALLDATETIME, columnName,105)))
Try this
SELECT DISTINCT YEAR(Convert(datetime,OrderCreatedDate,103)) from webshop
DD/MM/YYYY 00:00:00 AM (/PM) is the British format. See Convert