SQL Datetime Convert Error - sql

I have have an SQL Statement which returns following error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
SELECT * FROM eBV_Platz
WHERE (ADRID = 4436) AND (ID <> 5) AND (Status = 1)
AND (CONVERT(DATETIME, '01.03.2014', 102) >= PlaceFrom)
AND (CONVERT(DATETIME, '01.03.2014') <= PlaceTo)
OR (CONVERT(DATETIME, '31.03.2014') >= PlaceFrom)
AND (CONVERT(DATETIME, '31.03.2014') <= PlaceTo)
But this one works fine and the only difference are the date values:
SELECT * FROM eBV_Platz
WHERE (ADRID = 4436) AND (ID <> 5) AND (Status = 1)
and (CONVERT(DATETIME, '01.01.2000', 102) >= PlaceFrom)
AND (CONVERT(DATETIME, '01.01.2000') <= PlaceTo)
OR (CONVERT(DATETIME, '01.06.2001') >= PlaceFrom)
AND (CONVERT(DATETIME, '01.06.2001') <= PlaceTo)
I really don't understand this. Can anybody help me?

I'm betting that the second one does not work fine, rather it converts your dates to january 06 and january 01.
You need to give it a hint that you are using a day month year format.
Try instead:
(CONVERT(DATETIME, '31.03.2014', 103)
The 103 (from MSDN) interprets the date as dd/mm/yy
As #AlexK noted in the comments, these dont really need to be converted. You could simply use the strings as long as they were in a better format.
My assumption here is that you are using MSSQL. For a different platform, the syntax would be different.

As stated in the comments, use ISO 8601 date format to specify dates (yyyy-mm-ddThh:mm:ss[.mmm]).
This would change '31.03.2014' to '2014-03-31T00:00:00.000' and remove any ambiguity.

Related

Convert string to date SQL Server

I have a query when I need to convert a string to datetime, I use
CONVERT(DATETIME, '')
but it's still not working. My column fechac is of type Datetime.
If I pass in for example '2019-11-20 00:03:56.120', the query works but I don't need the time because is a parameter from an application web and I send the date example '2019-11-20'. Thanks!
This is my query:
SELECT *
FROM table
WHERE cb.fechac = CONVERT(DATETIME, '2019-11-20');
Use the format yyyyMMdd. With the datetime datatype yyyy-MM-dd is ambiguous. Otherwise, use a style code:
CONVERT(datetime,'2019-11-20',126);
CONVERT(datetime,'20191120')
Reading a lot through the lines in the comments here, however, are you actually after..?:
WHERE fechac >= '20191120'
AND fechac < '20191121'
Final reading through the lines. it appears the OP is actuaklly passing a parameter (I assume of the data type date), therefore...
WHERE fechac >= #fechac
AND fechac < DATEADD(DAY, 1, #fechac)
This should work on any system, regardless of internationalization settings:
WHERE cb.fechac=convert(DATE,'20191120');
SELECT *
FROM table cb
WHERE cast(cb.fechac as date) = convert(date, '2019-11-20', 23)

Date conversion doesn't work in where clause

I am trying to query against the columns SOE (datetime field) and Answer (varchar field) from a table where NOT ALL Answer values are dates but some of them are. If I remove the datediff from the 'where' clause, I'm able to run the query just fine. But on including it, it errors out saying that 'Conversion failed when converting date and/or time from character string'.
For context, I'm using SQL Server 2014.
This is what my query looks like:
select ID,
convert(datetime, Answer, 121) as Answer,
datediff(dd,convert(datetime,
Answer, 121), SOE) as Days
from table
where Type in (1) and SOE between '2019-01-01' and '2019-03-31'
and FormLocation = 'M1005_INP_DISCHARGE_DT'
and PayorType = 'Medicare'
and Answer <> ' '
datediff(dd, convert(datetime, Answer, 121), SOE) <= 5
Any tips on how to resolve this would be appreciated.
Before doing the conversion to datetime make sure the data in the "Answer" field can be converted to date. Try this...
and ((isdate(Answer) = 1) and (datediff(dd, convert(datetime, Answer, 121), SOE) <= 5))
Since 2012 you can use try_convert().
...
datediff(dd, try_convert(datetime, Answer, 121), SOE) <= 5
...
try_convert() returns NULL if the conversion doesn't succeed. And so does datediff() then. So you might want to handle that case some way.
Using apply you can save yourself some repetitive code:
select ID,
answer_datetime as Answer,
datediff(day, answer_datetime, SOE) as Days
from table t cross apply
(values (try_convert(datetime, Answer, 121))) v(answer_datetime)
where Type in (1) and
SOE between '2019-01-01' and '2019-03-31' and
FormLocation = 'M1005_INP_DISCHARGE_DT' and
PayorType = 'Medicare' and
Answer <> ' ' and
datediff(day, answer_datetime, SOE) <= 5;
But you should really fix the data definitions so date/times are stored using the correct type.

Why does my query return records which doesn't meet the where clause conditions?

I have written a query which returns records with dates that are actually older than the mentioned date.
Declare #DateFrom date
Set #DateFrom= '02/Oct/2019'
SELECT 1, Convert(varchar(11), AppliedDateTime, 106)
FROM [MC_Tenders].[dbo].[AppliedWorks]
Where
Convert(varchar, AppliedDateTime,106) >= Convert(varchar, #DateFrom,106)
Applied dates are saved in table as datetime e.g. 2017-04-25 15:51:25.257
You are doing the comparison as strings rather than dates. Remove the conversion:
SELECT 1, Convert(varchar(11), AppliedDateTime, 106)
FROM [MC_Tenders].[dbo].[AppliedWorks]
WHERE AppliedDateTime >= #DateFrom;
Type 106 is dd mm yyyy. When you compare as strings, the strings are compared, not the dates. With format 106, the days are compared first, so: '18-10-2017' < '25-12-1900' because "1" < "2".
Just to finish Gordon Linoff's thought, your code should look something like this:
SELECT
1
, CAST(AppliedDateTime AS DATE) AS AppliedDate
FROM
[MC_Tenders].[dbo].[AppliedWorks]
WHERE
CAST(AppliedDateTime AS DATE) >= #DateFrom;
Edit: I'm assuming AppliedDateTime is actually stored as a datetime, or some data type other than DATE. The explicit CAST to the DATE type will strip out the time component and allow SQL to just compare the date component to your variable.

Sybase date comparison - Correct format?

I'm pretty new to Sybase and am writing a query to return results after a specified date, and also before a specified date. MM/DD/YYYY format
At the moment im doing..
SELECT *
From aTable
WHERE afterDate >= 08/07/2013
AND beforeDate <= 08/08/2013
I'm getting records back, but as I'm a Sybase newbie, I want to be sure Sybase is interpreting these dates correctly..
Their online doc is pretty bad for basic explanations on things like this!
Anyone able to confirm if what I have works, or does it need some formatting round the dates?
You'll need to convert the dates into DATETIME and tell sybase what the format is to be sure.
According to this documentation the code for MM/DD/YYYY is 101, so something like this:
SELECT *
FROM aTable
WHERE afterDate >= CONVERT(DATETIME,'08/07/2013',101)
AND beforeDate <= CONVERT(DATETIME,'08/08/2013',101)
You can see the difference by running the following select statements:
SELECT CONVERT(DATETIME,'08/07/2013',101) --MM/DD/YYYY (2013-08-07 00:00:00.000)
SELECT CONVERT(DATETIME,'08/07/2013',103) --DD/MM/YYYY (2013-07-08 00:00:00.000)
For any date-time field in sybase, instead of going through the convert function, there is a more direct approach.
SELECT *
From aTable
WHERE afterDate >= '2013-08-07'
AND beforeDate <= '2013-08-08'
The date has to be in the form 'YYYY-MM-DD'
If you want to add a time, it can be included along with the date. The date and the time have to be separated by a T.
Any date time field can be directly used using the format 'YYYY-MM-DDTHH:MM:SS'
Using the functions is too lengthy. Noone needs a bazooka to shoot a squirrel! :)
CAST( '2000-10-31' AS DATE )
will convert from text to date format....
I am assuming that your two fields (afterDate and beforeDate) are in Date format.
Your example would be:
SELECT *
From aTable
WHERE afterDate >= CAST( '08/07/2013' AS DATE )
AND beforeDate <= CAST( '08/08/2013' AS DATE )
Also, usually (but not always) a date range is on the SAME field. As I said, that is not true all the time and you may have a good reason for that.
The best approach is to use the ANSI standard which does not require any conversion: yyyymmdd (you can also include hh:mm:ss) for instance:
DateField1 >= "20150101" and DateFile1 <= "20150102"
You should decide which Input-Strings the user is going to use as parameter and then convert them and concatenate them like you want, unless it is Datetime it is not important which initial format it had, you can use it in a between-condition.
E. g. the user is from Europe and uses "DD.MM.YY" and "hh:mm" as an input parameter, I would convert and concatenate like this:
WHERE dateCol between convert(DATETIME,
convert(char(11),
convert(DATETIME, '01.06.14', 4), 16) || ' ' || '00:00', 8)
AND convert(DATETIME,
convert(char(11),
convert(DATETIME, '01.07.14', 4), 16) || ' ' || '16:00', 8)

another Conversion failed when converting datetime from character string

SELECT Asset.AssetID, AnsMaint.Answer, Convert(datetime, AnsMaint.Answer) as maintasdate
FROM Asset INNER JOIN
AssetAnswer AnsMaint ON AnsMaint.AssetID = Asset.AssetID INNER JOIN
AssetField FldMaint ON FldMaint.AssetFieldID = AnsMaint.AssetFieldID
WHERE FldMaint.FieldText = 'Maint. Agreement Term'
AND ISDATE(AnsMaint.Answer) = 1
AND Convert(datetime, AnsMaint.Answer) < DateAdd(d, 145, GetDate())
I get the error on the last part of the AND. If I comment the AND out, it works fine. My dates in the DB happen to be 10/10/2012 and are valid. IsDate should weed out anything that is not valid.
In DB the results (when I comment out the last line). I'm completely stumped.
106 10/10/2012 2012-10-10 00:00:00.000
115 10/10/2012 2012-10-10 00:00:00.000
MORE interesting tidbits. If I change the last AND line to
AND DateAdd(d, cast(Asset.MaintenanceFreq as int), Convert(datetime, AnsMaint.Answer)) < DateAdd(d, 45, GetDate())
it works. If I take out the 2nd parameter (the cast as int) and replace it with a number or a zero, it gives me the same error.
I'm stumped. Any help would be so much appreciated!
Oh, AssetMaint.Answer is a varchar field in the DB nothing I can do about that.
From the description, it sounds like the Answer column contains values for some records which can't be converted to a date, and SQL is choosing an execution plan which evaluates the CONVERT before the ISDATE.
Try using a CASE statement for the conversion instead:
WHERE FldMaint.FieldText = 'Maint. Agreement Term'
AND CASE ISDATE(AnsMaint.Answer)
WHEN 1 THEN Convert(datetime, AnsMaint.Answer, 103)
END < DateAdd(d, 145, GetDate())
It's a guess , but I'd say it was mm/dd/yyyy versus dd/mm/yyyy.
e.g. 10/10 is okay, but 20/10 or 10/20 might not be.
add the style parameter to the converts e.g.
Convert(datetime, AnsMaint.Answer,103)
You'll have to look up which one based on what ever date format is in your mis-typed field.