CAST Correct VARCHAR to DateTime - sql

Good Day
I am working of a existing SQL Server Database. What the developers did is to keep the Date and time separate. The Date is in DateTime format (what I want) but the time is incorrect. if it is 14:30 it shows as 1430 when its 09:25 shows as 925. I am trying tyo combine the date and time to have a Date Time view for an program I am writing on top of this database.
I have created the date as a normal date like this:
CASE
WHEN LEN(T0.BeginTime) = 3 THEN '0' + LEFT(T0.BeginTime, 1) + ':' + RIGHT(T0.BeginTime, 2)
ELSE LEFT(T0.BeginTime, 2) + ':' + RIGHT(T0.BeginTime, 2)
END AS 'NEW Start Time'`
The date now looks like it's the correct format but when I want to combine the date and time I get VARCHAR to DateTime error.
How can I fix this?
This is the error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value (ONLY RAN 804 RECORDS)
Thanks

This should do the trick, Hope it helps.
DECLARE #DateTime TABLE (
DateWithTime DATE,
BeginTime INT);
INSERT INTO #DateTime
VALUES ('2014-08-04', '1525'),
('2014-08-04', '525'),
('2014-08-04', '15'),
('2014-08-04', '5'),
('2014-08-04', '0'),
('2014-08-04', '90')
;WITH cte_BeginTimeFix
AS (
SELECT
CONVERT(VARCHAR(10), DateWithTime, 120) AS DateWithTime,
RIGHT('0000' + CAST(BeginTime AS VARCHAR(4)), 4) AS BeginTime
FROM #DateTime
)
, cte_DateString
AS (
SELECT DateWithTime,
BeginTime,
DateWithTime + ' ' + STUFF(STUFF('00:00:00.000', 4, 2, RIGHT(BeginTime, 2)), 1, 2, LEFT(BeginTime, 2)) AS DateTimeStr
FROM cte_BeginTimeFix
)
SELECT DateWithTime,
BeginTime,
CASE
WHEN ISDATE(DateTimeStr) = 1 THEN CAST(DateTimeStr AS DATETIME)
ELSE NULL
END AS DateTimeStr
FROM cte_DateString

A different approach is to convert the time column in minutes and add it to the date
DATEADD(minute, T0.BeginTime / 100 * 60 + T0.BeginTime % 100
, CONVERT(VARCHAR, T0.BeginDate, 112))
with that the length of the time column doesn't matter

This should work:
CONVERT
(
DATETIME,
CONVERT(VARCHAR,T0.Date,112) +
' ' +
CASE
WHEN ISNULL(T0.BeginTime,'0') = '0'
THEN '00:00'
ELSE
RIGHT
(
'00' + LEFT(T0.BeginTime,LEN(T0.BeginTime) - 3),
2
) +
':' +
RIGHT(T0.BeginTime,2)
END
)

Related

DateTime to time interval in T-Sql

I am working on an SSRS report and I need to display hourly data count in a table.
The hourly interval need to be displayed as 4:00pm - 5:00pm
I have a log table which has DateTime available with each transaction. This table refreshes daily.
I am grouping on the hour component of this timestamp to get the hourly count.
Is there any option available in SQL/SSRS for converting hourly value to 04:00pm- 05:00pm format?
I would recommend that you simply create a simple scalar function in SQL Server for this one. See following example:
CREATE FUNCTION DateTimeToHourInterval
(
#currentDateTime DATETIME
)
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE #nextHourDateTime DATETIME = DATEADD(HOUR, 1, #currentDateTime);
DECLARE #intervalStart VARCHAR(10) = REPLACE(REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(50), DATEADD(MINUTE, -1* DATEPART(MINUTE, #currentDateTime), #currentDateTime), 100), 7)), 'PM', ' PM'), 'AM', ' AM');
DECLARE #intervalEnd VARCHAR(10) = REPLACE(REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(50), DATEADD(MINUTE, -1* DATEPART(MINUTE, #nextHourDateTime), #nextHourDateTime), 100), 7)), 'PM', ' PM'), 'AM', ' AM');
RETURN #intervalStart + ' - ' + #intervalEnd
END
The function can now be used as follow:
SELECT dbo.DateTimeToHourInterval(GETDATE());
Use case statement:
SELECT CASE
WHEN DATEPART(hour,TransactionDateTime) = 0 THEN '12:00am-01:00am'
WHEN DATEPART(hour,TransactionDateTime) = 1 THEN '01:00am-02:00am' ...
END FROM your_table
Dynamic way:
SELECT CASE
WHEN DATEPART(hour,TransactionDateTime) >12 THEN cast (DATEPART(hour,TransactionDateTime) -12 as VARCHAR (2)) + ':00pm-' +cast(DATEPART(hour,TransactionDateTime) -11 as VARCHAR (2)) + ':00pm'
WHEN DATEPART(hour,TransactionDateTime) <12
cast (DATEPART(hour,TransactionDateTime) as VARCHAR (2)) + ':00am-' +cast(DATEPART(hour,TransactionDateTime)+1 as VARCHAR (2)) + ':00am'
WHEN DATEPART(hour,TransactionDateTime) =12
cast (DATEPART(hour,TransactionDateTime) as VARCHAR (2)) +':00pm-1:00pm'
END
FROM your_table
For corner case (11pm) handle am/pm using a nested case statement. check the datepart and return am/pm based on the results. I was not able to test the query since I am posting this from my smartphone.
Hope this helps
Use the below script to convert datetime to 12 hour format.
SELECT LEFT (STUFF(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,YourColumn,100),7)),7),6,0,''),2)+':00'+RIGHT (LTRIM(RIGHT(CONVERT(VARCHAR(20), YourColumn, 100), 7)),2)
+' - '+LEFT (STUFF(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar, DATEADD(hh, 1, YourColumn),100),7)),7),6,0,''),2)+':00'+RIGHT (LTRIM(RIGHT(CONVERT(VARCHAR(20), DATEADD(hh, 1, YourColumn), 100), 7)),2)
FROM YourTable
Sample output :

Convert string to Datetime

I've received a flat file and after parsing and inserting it in a table. I've a column which has dates in a format yyyyMMddhhmmss
Here, yyyy is year, MM is month, dd is day, hh is hours, mm is minute and ss is seconds part
I'm trying to convert this to DateTime type as mentioned below but not working for me
SELECT CAST(StrDate as DateTime) FROM [dbo].[Mytable]
For example:
Column has a value 20150121190941 in Varchar format and it should be converted to DateTime as 2015-01-21 19:09:41.000
I apologize if it's a duplicate one.
You can use select DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
declare #dt nvarchar(25) = '20150121190941'
select datetimefromparts(left(#dt,4), substring(#dt,5,2), substring(#dt,7,2),substring(#dt,9,2), substring(#dt,11,2), substring(#dt,13,2), '000')
SQL Server readily recognizes YYYYMMDD as a date. So, converting the first 8 characters to a date is easy. Alas, I don't think there is a time representation without colons.
So, here is one rather brutal method:
select (convert(datetime, left(StrDate, 8)) +
convert(time, substring(StrDate, 9, 2 ) + ':' + substring(StrDate, 11, 2 ) + ':' + substring(StrDate, 13, 2 )
)
)
Declare #dt varchar(50)
set #dt=20150121190941
create table tblDateTbl
(
col1 datetime
)
insert into dt (col1)
select SUBSTRING(#dt,1,4) + '-' + SUBSTRING(#dt,5,2) + '-' + SUBSTRING(#dt,7,2)+ ' ' + SUBSTRING(#dt,9,2)+ ':' + SUBSTRING(#dt,11,2)+ ':' + SUBSTRING(#dt,13,2)+ '.000'

Need to format char(4) hhmm to time only or text to look like hh:mm in sql

In the script below, How do I convert the column HHMM to HH:MM and
convert it to 12hr clock?
The column is a char(4) and format 0000 - 2359.
Just want time or text with a colon(:), no date.
Please note that I do not want date or seconds. How do I do this?
Thank you for your help!
Select
th.[store] as 'My Store',
---> this column th.hhmm as Time, (I need this to format hh:mm)
emp.[First Name],
td.Type as [Total],
Count(*) as Qty,
Convert(varchar(50),SUM(Amount1),1) AS Amount
Try this. It uses LEFT and RIGHT functions
declare #time char(4)='2359'
select left(convert(varchar(100),cast(concat(left(#time,2),':',right(#time,2)) as time),9),5)+
' '+
right(convert(varchar(100),cast(concat(left(#time,2),':',right(#time,2)) as time),9),2)
SQL Server:
right('00' + cast((cast(substring(th.hhmm, 1, 2) as int) - 1) % 12 + 1 as varchar(2)), 2) +
':' + substring(th.hhmm, 3, 2) +
case when cast(substring(th.hhmm, 1, 2) as int) >= 12 then 'pm' else 'am' end
You can use substr to do this in Oracle.
select substr(th.hhmm,1,2)||':'||substr(th.hhmm,3,2) from t
In SQL Server, you can use substring
select substring(th.hhmm,1,2)+':'+substring(th.hhmm,3,2) from t
Fiddle with sample data
Edit:
select
case when cast(substring(th.hhmm,1,2) as int) < 12 then
case when cast(substring(th.hhmm,1,2) as int) = 0 then
'12'+':'+substring(th.hhmm,3,2)+' AM'
else substring(th.hhmm,1,2)+':'+substring(th.hhmm,3,2)+' AM' end
when cast(substring(th.hhmm,1,2) as int) > 12 then
cast(substring(th.hhmm,1,2)%12 as varchar(2)) +':'+substring(th.hhmm,3,2)+' PM'
when cast(substring(th.hhmm,1,2) as int) = 12 then
substring(th.hhmm,1,2)+':'+substring(th.hhmm,3,2)+' PM'
end

SQL conversion from varchar to datetime

One of the columns of my SQL Server table is mm:ss of varchar type where mm = minutes and ss = seconds.
I need to get the average of that column.
Should I convert that column to datetime format first? If so can you tell me how? If not can you tell me what I should do?
Here is my failed attempt to convert it to datetime :
SELECT CONVERT(DATETIME, '2014-01-01 '+Pace+':00', 108)
Where pace is a varchar like 23:05
If you want the average, I would convert the column to number of seconds and work with that:
select avg(pace_secs) as average_in_seconds
from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs
from t
) t;
If you want this back in the format, then you can do:
select right('00' + cast(avg(pace_secs) / 60 as int), 2) + ':' +
right('00' + avg(page_secs) % 60), 2)
from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs
from t
) t;
declare #pace varchar(20) = '23:05 ';
SELECT cast( '2014-01-01 '+cast(#pace as varchar(5))+':00' as datetime)
For SQL2012 and later
SELECT
FORMAT(DATEADD(second,AVG(DATEDIFF(second,0,'00:'+[Pace])),0),'mm:ss')
FROM MyTable

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.