Can't convert YYYYMMDD to date - sql

I'm trying to view software that has been installed within the last 30 days. The format of my date is 20150327. When I try to the following condition in the where clause
and DateDiff(day,arp.InstallDate0,GetDate()) < 30
I receive the following error message:
Conversion failed when converting date and/or time from character
string.
I have also tried the following and was unsuccessful:
CONVERT(varchar(8),arp.InstallDate0,112)
As well as:
ISDATE(CONVERT(datetime,arp.InstallDate0,112))
When I add ISDATE, it finally runs the query, but it is not showing any data and I know that there are installs within the last 30 days, so I'm thinking the date is still not being recognized.
EDIT The InstallDate0 column is nvarchar.

You do not need a conversion format for YYYYMMDD when converting to date, datetime2, and datetimeoffset. SQL Server recognizes this ISO standard format with no conversion in these cases, regardless of internationalization settings (there is one setting that affects my preferred format of YYYY-MM-DD; the documentation is here). So, you could do:
where cast(arp.InstallDate0 as date) > dateadd(day, -30, getdate())
At this point: "Shame on you for storing dates as strings."
That said, it is better (in your case) to do the comparison as strings rather than dates. You have a good date format for this, so:
where arp.InstallDate0 > convert(varchar(8), dateadd(day, -30, getdate()), 112)
Why is this better? With no functions on the column name, the query can take advantage of an appropriate index (if one is available).

You must use the syntax below, as the first argument for the CONVERT function is the target data type
CONVERT(datetime,'20150327',112)

You must use the syntax below:
WHERE
DATEDIFF(day, CONVERT(datetime, arp.InstallDate0, 112), GetDate()) < 30

Try converting the format using a converter to convert it to a date/or time string through conversion of its characters, then using the string to convert the numbers into a more usuable format with additional conversion
CONVERT(datetime,'20150327',112)

Related

SQL, casting a string to date so I can use GETDATE()

I am using SQL Server Management Studio 18 against SQL Server 2016. I have some material that are in batches and those batches have expiration dates that are held as strings, but are basically in the format of 'yearmonthday', e.g. '20210312' for March 3rd, 2021. My goal is to only see material that is expiring after the current date. Whenever I try to CAST the expiration date column AS DATE within the WHERE clause, I get this error:
Conversion failed when converting date and/or time from character string
(or something similar when trying different methods).
So, right now my code looks like this:
SELECT MaterialColumn, BatchColumn, CAST(ExpirationColumn AS DATE)
FROM StockTable
WHERE CAST(ExpirationColumn AS DATE) > CAST(GETDATE() AS DATE)
If I don't do the WHERE clause, I know I can CAST the ExpirationColumn as DATE without issue, but when it's in the WHERE clause, I run into that error. Is there any way I can filter to see only the dates that I want?
You can use try_cast() instead:
SELECT MaterialColumn, BatchColumn, CAST(ExpirationColumn AS DATE)
FROM StockTable
WHERE TRY_CAST(ExpirationColumn AS DATE) > CAST(GETDATE() AS DATE);
You can also find the bad values:
SELECT ExpirationColumn
FROM StockTable
WHERE TRY_CAST(ExpirationColumn AS DATE) IS NULL AND ExpirationColumn IS NOT NULL;
It sounds like you might need to fix some data values.
Honestly, if your dates are all stored in the format yyyyMMdd then there's no need to convert. Instead use a varchar parameter, as (at least) a varchar in the format yyyyMMdd had the same sort order as a date.
As a result you just convert GETDATE to the right format:
WHERE Expiration > CONVERT(varchar(8), GETDATE(), 112)
Of course, this doesn't change my statements in the comment; fix your design, don't stores dates as a string but as a date (and time) data type.

Convert date and/or time from varchar

How can I convert varchar string to date?
select CONVERT(date,'23/12/2019')
avoiding the following error:
Conversion failed when converting date and/or time from character string
Thanks
If you are using SQL Server (as suggested by the use of CONVERT() for this purpose), you can use CONVERT() with a third argument to specify DD/MM/YYYY format. That argument is 'DD/MM/YYYY'. No. Wait. That would be too sensible. You want:
select CONVERT(date, '23/12/2019', 103)
You are doing right except one thing which is missing from your statement and that is date_style similant.
select CONVERT(date, '23/12/2019', [put the similant here])
Example
select CONVERT(date, '23/12/2019', 110)
Result
2019-12-23
for full understanding
Click Here

How to correct this delete query

I need to do a select query like this:
select *
from faults
where insertdate < DATEADD(DAY, -30, sessiondate)
The query should be correct but I get this error:
Conversion failed when converting date and/or time from character string.
Since, sessiondate contains a date but as string and not in date format.
Is there a way to do this query with a string instead of a date type?
The error seems pretty clear. insertdate and/or sessiondate are stored as strings. You should fix the data.
SQL Server has three ways to convert such values:
Implicitly by putting the strings in a place where date/times are expected.
Explicitly using CAST()/CONVERT().
Explicitly and flexibly using PARSE().
You need to figure out what your format is. They you can convert it. You've provided no information, but a typical method would be:
where insertdate < DATEADD(DAY, -30, TRY_CONVERT(date, sessiondate, <date style here>))
Usually the formats available with CONVERT() are sufficient (see here). Sometimes, you may need to use TRY_PARSE().
EDIT:
To support timestamps, then you need to convert to datetime2:
try_convert(datetime2, '2019-07-08T09:17:19+02:00')
You should be comparison to a value with a timestamp.

Why does SQL Server convert VARCHAR to DATETIME using an invalid style?

I can't make out from the documentation why SQL Server parses a text in a format other than the specified style.
Regardless of whether I provide text in the expected format:
SELECT CONVERT(DATETIME, N'20150601', 112)
or incorrect format (for style 113):
SELECT CONVERT(DATETIME, N'20150601', 113)
The results are the same: 2015-06-01 00:00:00.000 I would expect the latter to fail to convert the date (correctly).
What rules does it employ when trying to convert a VARCHAR to DATETIME? I.e. why does the latter (incorrect format style) still correctly parse the date?
EDIT: It seems I've not been clear enough. Style 113 should expect dd mon yyyy hh:mi:ss:mmm(24h) but it happily converts values in the format yyyymmdd for some reason.
Because the date is in a canonical format ie(20150101). The database engine falls over it implicitly. This is a compatibility feature.
If you swapped these around to UK or US date formats, you would receive conversion errors, because they cannot be implicitly converted.
EDIT: You could actually tell it to convert it to a pig, and it would still implicitly convert it to date time:
select convert(datetime,'20150425',99999999)
select convert(datetime,'20150425',100)
select convert(datetime,'20150425',113)
select convert(datetime,'20150425',010)
select convert(datetime,'20150425',8008135)
select convert(datetime,'20150425',000)
And proof of concept that this is a compatibility feature:
select convert(datetime2,'20150425',99999999)
Although you can still implicitly convert datetime2 objects, but the style must be in the scope of the conversion chart.
Reason why is the date N'20150601' converted to valid datetime is because of fact that literal N'20150601' is universal notation of datetime in SQL Server. That means, if you state datetime value in format N'yyyymmdd', SQL Server know that it is universal datetime format and know how to read it, in which order.
You should convert to varchar type in order to apply those formats:
SELECT CONVERT(varchar(100), CAST('20150601' as date), 113)
OK, you are converting datetime to datetime. What did you expect? In order to apply formats you should convert to varchar and you have to have date or time type as second parameter.

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)