Varchar date to datetime sql - sql

I have a varchar date format of 01012018, I need to convert this to a date in a SQL Server view:
CONVERT(VARCHAR(50), CONVERT(DATE, [Date], 103), 103)
I have tried the above with no joy.
Please help

SQL Server can be a bit cumbersome when parsing dates that are not one of the "built-in" ones. You can use parse()/try_parse(), but that is a relatively new function.
In your case, it is pretty simple to construct the date value directly:
select convert(date, concat(right(ddmmyyyy, 4), substring(ddmmyyyy, 3, 2), left(ddmmyyyy, 2)))
from (values ('01012018')) v(ddmmyyyy)

There is no style ddMMyyyy in the CONVERT Date and Time Styles, but there is a dd/MM/yyyy, so you could inject these characters in and convert:
SELECT TRY_CONVERT(date, STUFF(STUFF(v.ddmmyyyy, 5, 0, '/'), 3, 0, '/'), 103)
FROM (VALUES ('01012018')) v (ddmmyyyy);
I've also used TRY_CONVERT incase you have some other "bad" values (perhaps '01312019'). These will return NULL when the varchar represents an invalid date.

Use CONVERT() as
DECLARE #Var VARCHAR(10) = '01012018'
SELECT CONVERT(DATE,
CONCAT( RIGHT(#Var, 4),
SUBSTRING(#Var, 3, 2),
LEFT(#Var, 2)
)
)
Demo
Finally, I would recommend ALTERing your table (which is the right solution) and change the data type of your column to DATE data type.
CREATE TABLE T(
MyCol VARCHAR(10)
);
INSERT INTO T(MyCol) VALUES
('01012018'),
('01022018'),
('01032018'),
('WrongData');
SELECT MyCol
FROM T;
UPDATE T
SET MyCol = TRY_CONVERT(DATE,
CONCAT( RIGHT(MyCol, 4),
SUBSTRING(MyCol, 3, 2),
LEFT(MyCol, 2)
)
);
ALTER TABLE T
ALTER COLUMN MyCol DATE;
SELECT MyCol
FROM T;
Second Demo

Related

Formatting date issue

I have the following query:
SELECT ACCOUNTNUMBER, PROCESSDATE
FROM INVENTORY
Result:
ACCOUNT PROCESSDATE
5646546 11082021
4654646 11082021
The date is in the wrong format.
NOTE: I checked the table design and the PROCESSDATE field seems to be an integer.
What code I have tried:
.-format(PROCESSDATE, 'DD/mm/yyyy') as PROCESSDATE [the result is DD/mm/yyyy in the column)
.-CONVERT(date, CONVERT(varchar(6), PROCESSDATE) + '01') myDate [The result is an error]
.-CONVERT(CHAR(10), PROCESSDATEAS Datetime) as 'MyDateTime' [the result is an error]
Desired output: Obtain PROCESSDATE field as MM/dd/yyyy format.
This is a horrible format. Note that if the day is less than 10, then the length of the integer changes. Arggh!
So, my recommendation is to convert to an 8-character string (with a leading '0' if necessary), then construct a canonical date string ('YYYYMMDD'). And convert to a date:
select convert(date,
right(format(processdate, '00000000'), 4) + substring(format(processdate, '00000000'), 3, 2) +left(format(processdate, '00000000'), 2)
)
You can actually move the format() to a subquery, CTE, or values clause, as in:
select convert(date, right(v.processdate_str, 4) + substring(v.processdate_str, 3, 2) +left(v.processdate_str, 2))
from inventory i cross apply
(values (format(i.processdate, '00000000'))
) v(processdate_str)
Here is a db<>fiddle.
You could use DATEFROMPARTS to parse the parts and then format 101 to put in MM/DD/YYYY format. Something like this
SELECT ACCOUNTNUMBER,
PROCESSDATE,
calc.dt,
convert(varchar(12), calc.dt, 101) vc_with_date_format
FROM (values (5646546, 11082021),
(5646546, 11082021))
INVENTORY(ACCOUNTNUMBER, PROCESSDATE)
cross apply (values (datefromparts(right(PROCESSDATE, 4),
substring(cast(PROCESSDATE as char(8)),3,2),
left(PROCESSDATE, 2)))) calc(dt);
[EDIT] Without the virtual table (which was for demo only)
SELECT i.ACCOUNTNUMBER,
i.PROCESSDATE,
calc.dt,
convert(varchar(12), calc.dt, 101) vc_with_date_format
FROM INVENTORY i
cross apply (values (datefromparts(right(i.PROCESSDATE, 4),
substring(cast(i.PROCESSDATE as char(8)),3,2),
left(i.PROCESSDATE, 2)))) calc(dt);
ACCOUNTNUMBER PROCESSDATE dt vc_with_date_format
5646546 11082021 2021-08-11 08/11/2021
5646546 11082021 2021-08-11 08/11/2021
I think your dates are stored as ddMMyyyy in the DB. You can get the desired result by applying the following conversion:
CONVERT(VARCHAR, CONVERT(DATETIME,STUFF(STUFF(PROCESSDATE, 5, 0, '/'), 3, 0, '/'),103), 101)

I have date stored in varchar in SQL Server as '19-09-2020' and I want to convert it to '2020-09-19'

I have date stored in a varchar column in SQL Server as '19-09-2020'.
I want to convert it to '2020-09-19'.
I have tried this but it's not working:
select convert(varchar, '19-09-2020', 23)
You must specify the source format for convert:
convert(date, '19-09-2020',105)
This results in a DATE, if you actually want a VarChar again (of course, you shouldn't):
convert(varchar(10), convert(date, '19-09-2020',105), 23)
Do you want string functions?
select concat_ws('-', right(mycol, 4), substring(mycol, 4, 2), left(mycol, 2))
from mytable
On the other hand, if you want to generate a date from that string, then:
select convert(date, mycol, 105)
from mytable

SQL Server - How to convert varchar to date

I have a table containing StartDate in the format dd/mm/yyyy and yyyy-mm-dd.
I want to convert this varchar column to DATE type in the format DD/MM/YYYY.
I have tried the below.
select CONVERT(varchar(20),StartDate,103) AS [FormattedDate]
and
CONVERT(VARCHAR(20),(CAST([StartDate] AS DATE)),103)
I get the error -Conversion failed when converting date and/or time from character string.
Pls suggest.
if you only have the date string in dd/mm/yyyy or yyyy-mm-dd
select case when substring(StartDate, 3, 1) = '/'
then convert(date, StartDate, 103)
else convert(date, StartDate, 121)
end
SQL Server is actually quite good about figuring out formats for a date conversion with no formatting argument. However, it is going to assume MM/DD/YYYY for the second format and generate an error.
So, you can use try_convert() and coalesce():
select coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
)
Here is a SQL Fiddle.
Then, you should go into your data and fix the column. Here is one method:
update t
set startdate = coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
);
alter table t alter column startdate date;
You can add additional formatting for the result set by turning the date back into a string, using convert().
To get YYYY-MM-DD use SELECT CONVERT(varchar, getdate(), 23)
To get MM/DD/YYYY use SELECT CONVERT(varchar, getdate(), 1)
For detailed explaination try this.
Here's an example that first tries to convert the VARCHAR from a 'yyyy-mm-dd' format to the 'dd/mm/yyyy' format.
If that doesn't work out, then it just assumes it's already in the 'dd/mm/yyyy' format.
And then defaults to the first 10 characters from the string.
declare #TestTable table (StartDate varchar(10), DateFormatUsed varchar(10));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate() ,103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
;
select t.*,
coalesce(convert(varchar(10), try_convert(date,StartDate,20),103), left(StartDate,10)) as [FormattedDate]
from #TestTable t;
But try_convert is only available since MS SQL Server 2012.
For MS SQL Server 2008 we can use a CASE WHEN with a LIKE to check the format.
declare #TestTable table (StartDate varchar(30), DateFormatUsed varchar(30));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate(), 103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
,(convert(varchar(19),GetDate(), 20), 'yyyy-mm-dd hh:mi:ss')
;
select t.*,
(case
when StartDate like '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'
then convert(varchar(10), convert(date, left(StartDate, 10), 20), 103)
else left(StartDate, 10)
end) as [FormattedDate]
from #TestTable t;

combine 2 varchar column's data and convert to datetime

I have 2 columns in a table of varchar datatype.
date and type are the column names in table.
the data present in the table looks like this
date time
20090610 132713
20090610 132734
i need ms sql server query to concatenate these 2 columns data and display as datetime format.
Note :
1. the datatype of those 2 columns cannot be changed now.
2. i tried
select convert(datetime,date + time)
it says "Conversion failed when converting date and/or time from character string."
Suggest the possible solution.
This will return a datetime. The bottom line is to be replaced by your table
select convert(datetime,date,112)+
coalesce(stuff(stuff(rtrim(time), 5,0,':'), 3,0,':'), '') newdate
from
(VALUES ('20090610','132713'),('20090610', '132734'),('20090610', ' ')) yourtable(date,time)
Result:
newdate
2009-06-10 13:27:13.000
2009-06-10 13:27:34.000
2009-06-10 00:00:00.000
You can get it using
SELECT
convert(varchar, convert(datetime, date), 111)
+ ' ' + substring(time, 1, 2)
+ ':' + substring(time, 3, 2)
+ ':' + substring(time, 5, 2)
CREATE TABLE #Table
(
[date] VARCHAR(100),
[time] VARCHAR(100)
)
INSERT INTO #Table VALUES
('20090610','132713'),
('20090610','132734')
;WITH Bits_CTE
AS
(
SELECT
[Date],
[Time],
[hrs] = CONVERT(INT,SUBSTRING([Time], 1, 2)),
[mns] = CONVERT(INT,SUBSTRING([Time], 3, 2)),
[secs] = CONVERT(INT,SUBSTRING([Time], 5, 2))
FROM #Table
)
SELECT
[Date],
[Time],
DATEADD(HOUR,[hrs],
DATEADD(MINUTE,[mns],
DATEADD(SECOND,[secs],[Date])))
FROM Bits_CTE
CREATE FUNCTION [dbo].[DateTimeAdd]
(
#datepart date,
#timepart time
)
RETURNS datetime2
AS
BEGIN
RETURN DATEADD(dd, DATEDIFF(dd, 0, #datepart), CAST(#timepart AS datetime2));
END
Sorry - Missed the bit in your question about storing the date and time as varchars. You would therefore still need to convert these data itemsbefore using this function.

SQL Server: Date conversion problem?

I have a column which has date-values stored in varchar (format ddmmyy) like this
231280
121280
131185
...
How to convert these values into datetime data type?
Set DateFormat DMY
GO
Select Cast(Stuff(Stuff(SomeValue, 3, 0, '-'), 6, 0, '-') As datetime)
From MyData
Use substring to get year, month, and day, if year greater than 11 add 19 to it if not add 20, to get year in format 2009, but this is your query just instead of string add your column name
select CAST(
CASE WHEN CAST(SUBSTRING('231280', 5, 2) AS INT) >11
THEN '19'+SUBSTRING('231280', 5, 2)
else '20'+SUBSTRING('231280', 5, 2)
END
+'-'+SUBSTRING('231280', 3, 2)+'-'+SUBSTRING('231280', 1, 2) as datetime)
You'd have to use some substring footwork to convert your string to a known date format. Here's an example converting the string to format 3, "British/French":
declare #YourTable table (YourColumn varchar(50))
insert #YourTable
select '231280'
union all select '121280'
union all select '131185'
select convert(datetime, substring(YourColumn,1,2) + '/' +
substring(YourColumn,3,2) + '/' + substring(YourColumn,5,2), 3)
from #YourTable
Because this format is non standard, use
DECLARE #field char(6)
SET #field = '231280'
select convert(datetime, right(#field, 2) + substring(#field, 3, 2) + left(#field, 2) , 12)