How do I convert date like '31/06/2013' or '30/02/2013' of datatype varchar in SQL Server 2008 - sql

I have a column named next_due_date datatype varchar and in this column some non-existing dates like 31/06/2012 or 30/02/2013 are saved. Because of this I get an error message when I convert it to date datatype.
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

If you dates would be valid (not something like the 31st of June or 30th of February - those dates simply don't exist!), then you could easily use the CONVERT function to convert them to DATE:
DECLARE #DateTable TABLE (DateColumn VARCHAR(20))
-- **VALID** dates - 30th of June, 28th of Feb
INSERT INTO #DateTable(DateColumn) VALUES ('30/06/2012'), ('28/02/2013')
-- easily converted to DATE type using style #104
SELECT DateColumn, CONVERT(DATE, DateColumn, 104)
FROM #DateTable

You can use try_parse (which is only available on higher SQL version, from 2012 on wards). It checks if a date is valid. If so, it returns the date, else null.
I think en-GB is the culture you need:
select try_parse('30/06/2012' as date using 'en-GB') -- returns a valid date
select try_parse('31/06/2012' as date using 'en-GB') -- returns null
If you need this on lower platforms, I would suggest to parse it by hand using a procedure. Something like this:
BEGIN TRY
select CONVERT(date,'31/06/2012',103)
END TRY
BEGIN CATCH
select null
END CATCH

Related

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 Numeric to Date in MS SQL

There is already a Datecolumn in Table which is in Numeric DataType(Converted to Int for faster ODBC Transfer), How can i convert that number to Data again?
Example the Values are like
42508
42826
43191
42158
42527
Which are nothing but like
SELECT CONVERT(numeric, getdate())
Query Result
43571
Just want to know how can i convert back that to normal date ?
You may use next conversion:
SELECT CONVERT(date, DATEADD(day, 43570, 0))
which will output:
17/04/2019 00:00:00
In this case SQL Server will use implicit data type conversion, because DATEADD() allows datetime datatype as third parameter and DATEADD() will convert 0 to 1900-01-01.

Dutch varchar date issue in SQL server 13 month

I have the following datetime format ( as varchar ) in my database 13-04-2018 1:05:00.
I need to convert it to the following format: 2018-04-13 01:05:00. As datetime.
Normal convert functions can't do this because they try to take the 13th month, and that month doesn't exist. This error:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
Does someone know how to convert this date issue?
Using datetimes is always a pain regardless of the language because of all the different formats across the world.
To sort your issue out currently, you need to use a format style which is a third parameter to CONVERT. Personally what I would suggest here is to store as a datetime, because storing datetimes as strings is never a good idea. It just gets too messy later on, but if saved in the format you would like, it would be saved as yyyy-MM-dd hh:mm:ss
SELECT CONVERT(DATETIME, '13-04-2018 1:05:00',103)
You can create your own function to format it in your desired output string.
CREATE FUNCTION FormatMyDate
(#Date DATETIME) RETURNS VARCHAR(20)
AS
BEGIN
RETURN FORMAT(#Date,'yyyy-dd-MM hh:mm:ss')
END
And then you can call it in SELECT statements like this:
SELECT dbo.FormatMyDate(yourDateCol)
FROM yourTable
this takes the date from the format where month comes before day and reverses the 2 values (month and day)
SELECT CONVERT(DATETIME, '2018-13-04 01:05:00', 103);
Results:
2018-04-13 01:05:00.000
This should work for you requirement...
SELECT FORMAT(yourdate, 'yyyy-dd-MM')
Your Solution Bro...
DECLARE #d DATETIME = GETDATE()
SELECT FORMAT ( #d, 'MM-dd-yyyy hh:mm:ss', 'de-de' ) AS 'Hoping your result'

Convert VARCHAR to DATE in SQL SERVER

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.

convert to Date format in MM/YY?

I am converting date into MM/YY, but it is converted to varchar. How to change that back to datetime datatype?
select RIGHT(CONVERT(VARCHAR(8), e.[Start_Date], 3), 5) AS 'Month/Year'
from table1
I am converting date into MM/YY, but it is converted to varchar. How to change that back to datetime datatype?
does this mean you are updating back same field with varchar value.How this is possible ?
where is date field lost ?
Declare #i datetime =getdate()
select stuff(convert(varchar(10),#i,103),1,3,'')
My understanding is that you have a value like "01/13" (Jan 2013) and you want to produce a DATETIME from it.
DECLARE #mmyy VARCHAR(5) = '01/13';
SELECT CAST('20'+RIGHT(#mmyy, 2)+'-'+LEFT(#mmyy, 2)+'-01' AS DATETIME)
-- returns 2013-01-01 00:00:00.000
Of course since your year is 2 digit I have to make the assumption that it's in the 21st century.