Convert VARCHAR to DATE in SQL SERVER - sql

I have VARCHAR column (MyValue) in my table. It has date value in two different format.
MyValue
----------
25-10-2016
2016-10-13
I would like to show them in DATE format.
I wrote query like below:
SELECT CONVERT(date, MyValue, 105) FROM MyTable
SELECT CAST(MyValue as date) FROM MyTable
Both are giving me this error. Conversion failed when converting date and/or time from character string.
Is there anyway convert to DATE datatype format even the value stored in different formats like above?
Expecting your answers. Thanks in advance.

Does this help?
declare #varchardates table
(
vcdate varchar(20)
)
INSERT INTO #varchardates VALUES
('25-10-2016'),
('2016-10-13')
SELECT CONVERT(date,vcdate, case when SUBSTRING(vcdate, 3, 1) = '-'
THEN 105 ELSE 126 END) as mydate
FROM #varchardates
Depending on how many different formats you have in your data, you may need to extend the case statement!
See here for list of the different format numbers

You can use TRY_CONVERT and COALESCE. TRY_CONVERT returns NULL if the conversion fails, COALESCE returns the first NOT NULL value:
SELECT COALESCE(TRY_CONVERT(DATETIME, x, 105), TRY_CONVERT(DATETIME, x, 120))
FROM (VALUES('25-10-2016'), ('2016-10-13')) a(x)
I assumed the value 2016-10-13 is in format yyyy-MM-dd.
You mention in a comment you may have other formats as well. In that case it gets very tricky. If you get a value 01-12-2017 and you have no idea about the format, there is no way to tell whether this is a date in januari or in december.

Related

Conversion from INT to varchar in sql

I have a table where there are values like 20170730 and also 0 values are there which is INT type
I am trying to convert it to value like 30/07/2017, for which i am using the below code,
Select convert(NVARCHAR(10),convert(date,convert(NCHAR(8),datecolumn)),103) from table
But for the zero values i am getting the below error
Conversion failed when converting date and/or time from character string.
If i delete all the zero this working fine but problem having with zero.
My requirement is to convert when there a date value and if 0 are there then it should be zero only like below,
Result
30/07/2017
0
Can u pls help
As already pointed out in the comments, you can try to use a CASE expression
SELECT CASE
WHEN nmuloc = 0 THEN
'0'
ELSE
convert(varchar(10),
convert(date,
convert(varchar(8),
nmuloc),
112),
103)
END
FROM elbat;
or try_convert() and coalesce().
SELECT coalesce(convert(varchar(10),
try_convert(date,
convert(varchar(8),
nmuloc),
112),
103),
'0')
FROM elbat;
db<>fiddle
The latter one will also correct other "malformed" data like 123 for example. The former will also fail in such cases. You may want that or not.
But, as also already pointed out in the comments, your real problem is that you use an inappropriate data type. Change the column's datatype to some date/time data type to really fix this.

Error when converting varchar to date ddmmyyyy

I have a varchar column with the following format ddmmyyyy and I'm trying to convert it to date in the format dd-mm-yyyy. I'm using the query below but I get the error:
Conversion failed when converting date and/or time from character string.
select *, coalesce(try_convert(date, newdate, 105), convert(date, newdate))
from mydate
You don't have a date, you have a string. So, you can use string operations:
select stuff(stuff(newdate, 5, 0, '-'), 3, 0, '-')
If you want to convert to a date, you can do:
select convert(date, concat(right(newdate, 4), substring(newdate, 3, 2), left(newdate, 2)))
You could then format this as you want.
However, you should not be converting the value to a date. You should be storing it as a date in the first place.
To turn your string to a date, you can just [try_]cast() it; SQL Server is usually flexible enough to figure out the format by itself:
try_cast(newdate as date)
If you want to turn it back to a string in the target format, then you can use format():
format(try_cast(newdate as date), 'dd-MM-yyyy')
Compared to pure string operations, the upside of the try_cast()/format() approach is that it validates that the string is a valid date in the process.
Have to agree with the others. Why are you storing a date as a string in the first place? In a non-standard format, no less? Here's one way, but you should really fix the data model. Store dates as dates.
DECLARE #badIdea table (dt char(8));
INSERT #badIdea(dt) VALUES('21052020');
SELECT newdate = TRY_CONVERT(date, RIGHT(dt,4) + SUBSTRING(dt,3,2) + LEFT(dt,2))
FROM #badIdea;
BTW 105 won't work because it requires dashes. This works:
SELECT CONVERT(date, '21-05-2020', 105);
That's a bad format too, IMHO, because who knows if 07-08-2020 is July 8th or August 7th. But at least that one is supported by SQL Server. Your current choice is not.
SQL doesn't store date data types in different formats, and it's probably not a good idea to try and adjust this.
If, however, you are wanting a result set to simply display the date in a different format, you are on the right track. You just need to convert your date data type to a string.
SELECT *
, COALESCE ( TRY_CONVERT ( CHAR(10), newdate, 105 ), CONVERT ( CHAR(10), newdate ) )
FROM mydate

Why isn't SQL Server letting me store '21/04/17' as a date?

I've got a table that currently has all columns stored as nvarchar(max), so I'm converting all the datatypes to be what they should be. I have a column of dates, however when I run this:
ALTER TABLE Leavers ALTER COLUMN [Actual_Termination_Date] date;
I get
"Conversion failed when converting date and/or time from character string".
This is relatively normal, so I did the following to investigate:
SELECT DISTINCT TOP 20 [Actual_Termination_Date]
FROM LEAVERS
WHERE ISDATE([Actual_Termination_Date]) = 0
which returned:
NULL
13/04/2017
14/04/2017
17/04/2017
19/04/2017
21/04/2017
23/04/2017
24/04/2017
26/04/2017
28/04/2017
29/03/2017
29/04/2017
30/04/2017
31/03/2017
42795
42797
42813
42817
42820
42825
The null and excel style date formats (e.g. 42795) are no problem, however it's the ones appearing as perfectly normal dates I'm having a problem with. I usually fix issues like this by using one of the following fixes:
SELECT cast([Actual_Termination_Date] - 2 as datetime)
FROM LEAVERS
WHERE ISDATE([Actual_Termination_Date]) = 0
or
SELECT cast(convert(nvarchar,[Actual_Termination_Date], 103) - 2 as datetime)
FROM LEAVERS
WHERE ISDATE([Actual_Termination_Date]) = 0
When these return back the dates as I would expext, I'd then do an UPDATE statement to change them in the table and then convert the column type. However I keep getting an error message telling me that various dates can't be converted such as:
Conversion failed when converting the nvarchar value '21/04/2017' to data type int.
Any thoughts? Thanks!
Probably because of your language setting. For '21/04/2017' to work, you'll need to be using the BRITISH language, or other language that uses dd/MM/yyyy. I suspect you are using ENGLISH which is actually American.
American's use MM/dd/yyyy meaning that '21/04/2017' would mean the 4th day of the 21st month in the year 2017; obviously that doesn't work.
The best method is to use an unambiguous format, regardless of language and data type. For SQL Server that's yyyyMMdd and yyyy-MM-ddThh:mm:ss.nnnnnnn (yyyy-MM-dd and yyyy-MM-dd hh:mm:ss.nnnnnnn are not unambiguous in SQL Server when using the older datetime and smalldatetime data types).
Otherwise you can use CONVERT with a style code:
SELECT CONVERT(date,'21/04/2017', 103)
The problem with your data, however, is that you have values that are in the format dd/MM/yyyy and integer values. The int (not varchar) value 42817 as a datetime in SQL Server is 2017-03-25. On the other hand, if this data came from Excel then the value is 2017-03-23. I am going to assume the data came from Excel, not SQL Server (because the ACE drivers have a habit of reading dates as numbers, because the thing they aren't is "ace").
You'll need to therefore convert the values to an unambiguous format first, so that'll be yyyyMMdd. As we have 2 different types of values, this is a little harder, but still possible:
UPDATE dbo.Leavers
SET Actual_Termination_Date = CONVERT(varchar(8), ISNULL(TRY_CONVERT(date, Actual_Termination_Date, 103), DATEADD(DAY, TRY_CONVERT(int, Actual_Termination_Date),'18991230')), 112);
Then you can alter your table:
ALTER TABLE dbo.Leavers ALTER COLUMN [Actual_Termination_Date] date;
DB<>Fiddle using MichaƂ Turczyn's DML statement.
Put the column into a canonical format first, then convert:
update leavers
set Actual_Termination_Date = try_convert(date, [Actual_Termination_Date], 103);
ALTER TABLE Leavers ALTER COLUMN [Actual_Termination_Date] date;
The update will do an implicit conversion from the date to a string. The alter should be able to "undo" that implicit conversion.
Back up the table before you do this! You are likely to discover that some dates are not valid -- that is pretty much the rule when you store dates as strings although in a small minority of cases, all date strings are actually consistently formatted.
The actual date does not matter. The error happens when you try to subtract 2 from a string:
[Actual_Termination_Date] - 2
The clue comes from the error message:
Conversion failed when converting the nvarchar value '21/04/2017' to data type int.
To fix the problem, use DATEADD after the conversion:
SELECT DATEADD(days, -2, convert(datetime, [Actual_Termination_Date], 103))
You just have inconsistent date format within your column, which is terrible.
Having wrong datatype lead to it, that's why it is so important to have proper data types on columns.
Let's investigate it a little:
-- some test data
declare #tbl table (dt varchar(20));
insert into #tbl values
(NULL),
('13/04/2017'),
('14/04/2017'),
('17/04/2017'),
('19/04/2017'),
('21/04/2017'),
('23/04/2017'),
('24/04/2017'),
('26/04/2017'),
('28/04/2017'),
('29/03/2017'),
('29/04/2017'),
('30/04/2017'),
('31/03/2017'),
('42795'),
('42797'),
('42813'),
('42817'),
('42820'),
('42825');
-- here we handle one format
select convert(date, dt, 103) from #tbl
where len(dt) > 5
or dt is null
-- here we handle excel like format
select dateadd(day, cast(dt as int), '1900-01-01') from #tbl
where len(dt) = 5
So, as you can see you have to apply to different approaches for this task. CASE WHEN statement should fit here nicely, see below SELECT:
select case when len(dt) = 5 then
dateadd(day, cast(dt as int), '1900-01-01')
else convert(date, dt, 103) end
from #tbl

Convert varchar containing various formats to DATETIME

I have a record_created column of type varchar containing multiple values formatted in two different ways throughout.
2017-04-17 16:55:53.3840460
Sep 18 2015 11:25PM
How can I convert this column into a DATETIME to be compared to GETDATE?
GETDATE() is SQL Server specific if so, then you can use try_convert() :
select cast(try_convert(datetime2, col) as datetime)
from table t
where try_convert(datetime2, col) is not null;
However, if the string date is exactly the same format which you have provide then you can simply do casting :
select cast(cast(col as datetime2) as datetime)
from table t;
If you are using SQL Server, then you may be able to use the CONVERT function here:
SELECT
CONVERT(datetime, LEFT('2017-04-17 16:55:53.3840460', 23), 121) AS date1,
CONVERT(datetime, 'Sep 18 2015 11:25PM', 100) AS date2;
Your first type of timestamp seems to work with mask 121, and the second one works with mask 100. The demo link below shows that the conversions are working.
Demo

Convert String to date in select statement

I have a column which contains data but the problem is that this column has data type of varchar(50) and it has to be this due to some reasons,now what i want to do is while selecting data from table , i want to treat this column as date so that i can use it in where clause. i am using the code below for converting it yo date , but it converts some values and then gives an error
this is my sample data
8/1/2002
6/9/2001
14/9/2001
26/7/2001
14/12/2001
21/1/2002
29/4/2001
7/5/2001
9/11/2001
16/7/2001
select CONVERT(date,sowingDate,103) from tblAgriculture_staging
I have tried which differnt version of date format e.g 103,105 etc
but still it converts some values but error comes on some values and query execution stops
Try this:
SET DATEFORMAT dmy;
select case when isdate(sowingDate) = 1 then CONVERT(date,sowingDate,103) end [date] from tblAgriculture_staging
or (if you are using sql 2012)
SET DATEFORMAT dmy;
select case when TRY_CONVERT(date, sowingDate) IS NOT NULL then CONVERT(date,sowingDate,103) end [date] from tblAgriculture_staging
but this solution hides (convert to NULL) all dates that are wrong. You can reverse the condition first and find/fix all rows with incorrect date (i.e. 31/02/2013) and then use this queries to show only valid dates
SQLFiddle
but it converts some values and then gives an error this is my sample
data
because some data are in invalid format or contains incorrect symbols.
Try this:
select CONVERT(date,ltrim(rtrim(sowingDate)), 103) from tblAgriculture_staging
or examine your values:
select ISDATE(sowingDate) as IsDate, sowingDate, CASE WHEN ISDATE(sowingDate)=1 THEN CONVERT(date,ltrim(rtrim(sowingDate)), 103) ELSE NULL END from tblAgriculture_staging
This is slightly crappy, but so is storing dates as varchar.
this is code that has worked for me in the past where i had some dates with 4 digit years and some with 2 digit years.
where (TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),1)>=#From
AND TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),1)<=#To)
OR (TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),101)>=#From
AND TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),101)<=#To)
SQL Server 2012 + Only
This assumes you have cleaned up anything that actually just isn't a date...
This will return all the dates that are not actually dates.
select sowingDate from tblAgriculture_staging where isdate(sowingDate)=0