SQL Server: Date conversion problem? - sql

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)

Related

Varchar date to datetime 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

How convert SQL Server DATE columns to DD:MM:YY and HH:MM:SS

I have a SQL Server column which is called DATE with this sample data 19452801102747.
I have this code
SELECT REPLACE(CONVERT(CHAR(10), [DATE], 103), '/', '')
I can get the date okay, is the final part of converting HH:MM:SS.
I am using SSMS 2018 and I would like to have two column separate; columns as shown on below image (DATE(DD:MM:YYYY))(TIME(HH:MM:SS))
Many thanks for your help.
We can use a simple substring to add date time separator in your varchar string,
because we cannot directly convert varchar to datetime..
DECLARE #date varchar(50) = '19452801102747' declare #date1 varchar(50)
SET
#date1 = SUBSTRING(#date, 1, 4) + '-' + substring(#date, 7, 2) + '-' + substring(#date, 5, 2) + ' ' + substring(#date, 9, 2) + ':' + substring(#date, 11, 2) + ':' + substring(#date, 13, 2)
SELECT convert(datetime, #date1)
First of all: You should not store datetime values in a non-appropriate datatype.
Your example looks like YYYYddMMHHmmss. There is no out of the box conversion for this...
The following will perform a number of string methods in order to transform your own format to a standard format. In this case I chose ISO8601, which is YYYY-MM-ddTHH:mm:ss:
DECLARE #YourDate VARCHAR(100)='19452801102747';
SELECT CONVERT(DATETIME,STUFF(LEFT(#YourDate,4) + STUFF(STUFF(STUFF(STUFF(SUBSTRING(#YourDate,7,1000),7,0,':'),5,0,':'),3,0,'T'),1,0,'-'),8,0,'-' + SUBSTRING(#YourDate,5,2)),126);
The STUFF() calls will insert some characters in the right position. Furthermore some string cutting will swap your ddMM to MMdd.

How to select numeric string as a valid DATE

CUSTOMER(ID,NAME,ENTRY_DT)
1,Dave,8312012
2,Tom,11262013
3,Iva,3312012
.
.
.
So the ENTRY_DT column has numeric string value in MDDYYYY or MMDDYYYY format.
I want to write a simple select query so that ENTRY_DT shows
8/31/2012
11/26/2013
3/31/2012
.
.
.
DECLARE #TABLE TABLE (Int_Date INT)
INSERT INTO #TABLE VALUES
(8312012),
(11262013),
(3312012)
SELECT LEFT(RIGHT('00000000'+ CAST(Int_Date AS VARCHAR(10)), 8), 2) +'/'
+REVERSE(SUBSTRING(REVERSE(Int_Date), 5, 2)) + '/' + RIGHT(Int_Date, 4)
FROM #TABLE
Result
08/31/2012
11/26/2013
03/31/2012
Select covert(date,right(('00000000' + entry_dt),8),101)
--- if it is SQL server 2008 or above
Replace date with date time if it is 2005 or below.
select id, name, CONVERT(datetime, entry_dt, 101)
SELECT LEFT(RIGHT('00000000'+CAST(ENTRY_DT AS VARCHAR(10)),8),2)+'/'+REVERSE(SUBSTRING(REVERSE(ENTRY_DT), 5, 2))+'/'+REVERSE(SUBSTRING(REVERSE(ENTRY_DT), 1, 4)) FROM #CUSTOMER
SELECT SUBSTRING(RIGHT('00000000'+ENTRY_DT,8),1,2)+'/'+SUBSTRING(RIGHT('00000000'+ENTRY_DT,8),3,2)+'/'+SUBSTRING(RIGHT('00000000'+ENTRY_DT,8),5,4) FROM #CUSTOMER

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.

How do I create a datetime from a custom format string?

I have datetime values stored in a field as strings. They are stored as strings because that's how they come across the wire and the raw values are used in other places.
For reporting, I want to convert the custom format string (yyyymmddhhmm) to a datetime field in a view. My reports will use the view and work with real datetime values. This will make queries involving date ranges much easier.
How do I perform this conversion? I created the view but can't find a way to convert the string to a datetime.
Thanks!
Update 1 -
Here's the SQL I have so far. When I try to execute, I get a conversion error "Conversion failed when converting datetime from character string."
How do I handle nulls and datetime strings that are missing the time portion (just yyyymmdd)?
SELECT
dbo.PV1_B.PV1_F44_C1 AS ArrivalDT,
cast(substring(dbo.PV1_B.PV1_F44_C1, 1, 8)+' '+substring(dbo.PV1_B.PV1_F44_C1, 9, 2)+':'+substring(dbo.PV1_B.PV1_F44_C1, 11, 2) as datetime) AS ArrDT,
dbo.MSH_A.MSH_F9_C2 AS MessageType,
dbo.PID_A.PID_F3_C1 AS PRC,
dbo.PID_A.PID_F5_C1 AS LastName,
dbo.PID_A.PID_F5_C2 AS FirstName,
dbo.PID_A.PID_F5_C3 AS MiddleInitial,
dbo.PV1_A.PV1_F2_C1 AS Score,
dbo.MSH_A.MessageID AS MessageId
FROM dbo.MSH_A
INNER JOIN dbo.PID_A ON dbo.MSH_A.MessageID = dbo.PID_A.MessageID
INNER JOIN dbo.PV1_A ON dbo.MSH_A.MessageID = dbo.PV1_A.MessageID
INNER JOIN dbo.PV1_B ON dbo.MSH_A.MessageID = dbo.PV1_B.MessageID
According to here, there's no out-of-the-box CONVERT to get from your yyyymmddhhmm format to datetime.
Your strategy will be parsing the string to one of the formats provided on the documentation, then convert it.
declare #S varchar(12)
set #S = '201107062114'
select cast(substring(#S, 1, 8)+' '+substring(#S, 9, 2)+':'+substring(#S, 11, 2) as datetime)
Result:
2011-07-06 21:14:00.000'
This first changes your date string to 20110706 21:14. Date format yyyymmdd as a string is safe to convert to datetime in SQL Server regardless of SET DATEFORMAT setting.
Edit:
declare #T table(S varchar(12))
insert into #T values('201107062114')
insert into #T values('20110706')
insert into #T values(null)
select
case len(S)
when 12 then cast(substring(S, 1, 8)+' '+substring(S, 9, 2)+':'+substring(S, 11, 2) as datetime)
when 8 then cast(S as datetime)
end
from #T
Result:
2011-07-06 21:14:00.000
2011-07-06 00:00:00.000
NULL
You can use CAST or CONVERT.
Example from the site:
G. Using CAST and CONVERT with
datetime data
The following example displays the
current date and time, uses CAST to
change the current date and time to a
character data type, and then uses
CONVERT display the date and time in
the ISO 8901 format.
SELECT
GETDATE() AS UnconvertedDateTime,
CAST(GETDATE() AS nvarchar(30)) AS UsingCast,
CONVERT(nvarchar(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO
Here is the result set.
UnconvertedDateTime UsingCast UsingConvertTo_ISO8601
----------------------- ------------------------------ ------------------------------
2006-04-18 09:58:04.570 Apr 18 2006 9:58AM 2006-04-18T09:58:04.570
(1 row(s) affected)
Generally, you can use this code:
SELECT convert(datetime,'20110706',112)
If you need to force SQL Server to use a custom format string, use the following code:
SET DATEFORMAT ymd
SELECT convert(datetime,'20110706')
A one liner:
declare #datestring varchar(255)
set #datestring = '201102281723'
select convert(datetime, stuff(stuff(#datestring,9,0,' '),12,0,':') , 112 )
Result:
2011-02-28 17:23:00.000
DECLARE #d VARCHAR(12);
SET #d = '201101011235';
SELECT CONVERT(SMALLDATETIME, STUFF(STUFF(#d,9,0,' '),12,0,':'));
Note that by storing date/time data using an inappropriate data type, you cannot prevent bad data from ending up in here. So it might be safer to do this:
WITH x(d) AS
(
SELECT d = '201101011235'
UNION SELECT '201101011267' -- not valid
UNION SELECT NULL -- NULL
UNION SELECT '20110101' -- yyyymmdd only
),
y(d, dt) AS
(
SELECT d,
dt = STUFF(STUFF(LEFT(d+'000000',12),9,0,' '),12,0,':')
FROM x
)
SELECT CONVERT(SMALLDATETIME, dt), ''
FROM y
WHERE ISDATE(dt) = 1 OR d IS NULL
UNION
SELECT NULL, d
FROM y
WHERE ISDATE(dt) = 0 AND d IS NOT NULL;
DECLARE #test varchar(100) = '201104050800'
DECLARE #dt smalldatetime
SELECT #dt = SUBSTRING(#test, 5, 2)
+ '/' + SUBSTRING(#test, 7, 2) + '/'
+ SUBSTRING(#test, 1, 4) + ' ' + SUBSTRING(#test, 9, 2)
+ ':' + SUBSTRING(#test, 11, 2)
SELECT #dt
Output:
2011-04-05 08:00:00