Retrieve duration query - sql

I have a MS SQL 2005 server. I have a database by name STAT & 2 columns by name STARTRUN & ENDRUN and have many rows in it.
STARTRUN ENDRUN
20110910200007 20110910200017
20110910200028 20110910200037
20110910200048 20110910200057
It shows the start time and end time of an activity and is in YYYYMMDDHHMMSS format. The datatype for this column is VARCHAR. I am trying to write a SQL script where i can retrieve the duration of each activity and dump it to a csv file as shown below.
START DATE START TIME END DATE END TIME DURATION
10-09-2011 8:00:07 PM 11-09-2011 1:10:10 AM 5:10:03
Please help me.

First you'd have to find a way to convert your format to a datetime. The subquery below does that by making it look like an ODBC canonical date and then calling convert. Then you can combine more convert with datediff to get your desired output format.
select convert(varchar, startrun, 105) + ' ' +
substring(convert(varchar, startrun, 109), 13, 8) + ' ' +
substring(convert(varchar, startrun, 109), 25, 2)
, convert(varchar, endrun, 105) + ' ' +
substring(convert(varchar, endrun, 109), 13, 8) + ' ' +
substring(convert(varchar, endrun, 109), 25, 2)
, substring('0' + cast(datediff(hh, startrun, endrun)
as varchar), 1, 2) + ':' +
substring('0' + cast(datediff(mi, startrun, endrun) % 60
as varchar), 1, 2) + ':' +
substring('0' + cast(datediff(s, startrun, endrun) % 60*60
as varchar), 1, 2)
from (
select convert(datetime,
substring(startrun,1,4) + '-' +
substring(startrun,5,2) + '-' +
substring(startrun,7,2) + ' ' +
substring(startrun,9,2) + ':' +
substring(startrun,11,2) + ':' +
substring(startrun,13,2),
120) as startrun
, convert(datetime,
substring(endrun,1,4) + '-' +
substring(endrun,5,2) + '-' +
substring(endrun,7,2) + ' ' +
substring(endrun,9,2) + ':' +
substring(endrun,11,2) + ':' +
substring(endrun,13,2),
120) as endrun
from #YourTable
) as SubQueryAlias
Here's a working example at SE Data. See this question for exporting the result of a query to a CSV file.

Related

Convert BigInt timestamp to just Date in SQL

I am facing a problem in conversion and type cast. I've a field which is of Data Type BigInt that has a value stored in the format "yyyymmddhhmmss" like "20170609043000". I am trying to get the substring of date part in the timestamp like 20170609 with a separator as 2017-06-09. Not able to fetch the date part in the timestamp.
Query I tried to fetch the Date part:
SELECT CONVERT(date,SUBSTRING(CAST(STR(evt.StartDate,15) as varchar),1, 5), 102) from Event evt
SELECT DATEADD(hour,-5, CONVERT(datetime, SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar),6, 2) + '-' + SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar), 8, 2) + '-' + SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar), 1,5) + ' ' + SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar),10, 2) + ':' +SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar), 12, 2) + ':' + SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar), 14, 2), 120)) from Event evt
The first query returns the converted date but the month and date remains same , concatenation doesn't work if I try to substring month and date.
Second query doesn't work at all.
Any help would be great.
Why not just take the 8 left most characters, and convert it?
SELECT CONVERT(date, LEFT(20170609043000,8));
Ideally though, you should be using a date and time datatype to store your date and time data. Storing them in a different data type only ends up causing problems and never solves a problem that can't be solved else where (aka your presentation layer).
Your second query is almost right but is getting the year, month, date in the wrong order. Try this instead:
SELECT CONVERT(datetime, SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar),2, 4) + '-' +
SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar), 6, 2) + '-' +
SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar), 8,2) + ' ' +
SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar),10, 2) + ':' +
SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar), 12, 2) + ':' +
SUBSTRING(CAST(STR(evt.StartDate, 15) as varchar), 14, 2), 120)
FROM Event evt
Output:
09/06/2017 04:30:00
Demo on dbfiddle

SQL Syntax Error When Adding Convert Function

This works
SELECT
LEFT(DATENAME(DAY, GETDATE()), 3) + '-' +
LEFT(DATENAME(MONTH, GETDATE()), 3) + ' ' + '-' +
RIGHT('00' + CAST(YEAR(GETDATE()) AS VARCHAR), 2)
This also works
SELECT CONVERT(TIME(0), GETDATE())
But when I combine both then I get an error
SELECT
LEFT(DATENAME(DAY, GETDATE()), 3) + '-' +
LEFT(DATENAME(MONTH, GETDATE()), 3) + ' ' + '-' +
RIGHT('00' + CAST(YEAR(GETDATE()) AS VARCHAR), 2) + ' '
CONVERT(TIME(0), GETDATE())
This doesn't answer your question, but your first query is overcomplicated. I don't understand the date format, but whatever you need, this is a simpler method:
SELECT DATENAME(DAY, GETDATE()) + '-' +
LEFT(DATENAME(MONTH, GETDATE()), 3) + ' -' +
RIGHT(DATENAME(YEAR, GETDATE()), 2)
Notes:
The DAY component is never more than 2 characters, so LEFT(. . . , 3) is unnecessary.
' ' + '-' can be simplified to ' -'.
You can use DATENAME() on the year as well.
You can try below - you need to add + operator and also cast it to varchar()
SELECT LEFT(DATENAME(Day,GETDATE()),3) + '-' +
LEFT(DATENAME(MONTH,GETDATE()),3) + ' ' + '-' +
RIGHT('00' + CAST(YEAR(GETDATE()) AS VARCHAR),2) + ' ' +
cast(convert(time(0),getDate()) as varchar(10))

How to convert date into DD-MON-YYYY HH24:MI:SS format?

Can someone help me with SQL Date format?
The following statement
SELECT convert(VARCHAR(20),GETDATE(),113)
returns
04 Aug 2011 08:08:08.
I want the results like
Aug-04-2011 08:08:08
Thank you!
SELECT
LEFT(DATENAME(MONTH, Date), 3) + '-' +
RIGHT(100 + DAY(Date), 2) + '-' +
DATENAME(YEAR, Date) + ' ' +
CONVERT(varchar, Date, 108)
FROM (SELECT Date = GETDATE()) s
Off the top of my head, I think its:
SELECT convert(VARCHAR(20),GETDATE(),120)
EDIT:
This will work:
SELECT datename(day, GETDATE()) + '-'
+ substring(datename(month, GETDATE()),0,4) + '-'
+ datename(year, GETDATE()) + ' '
+ datename(hh, GETDATE()) + ':'
+ datename(mi, GETDATE()) + ':'
+ datename(ss, GETDATE())
SECOND EDIT:
SELECT substring(datename(month, GETDATE()),0,4) + '-'
+ datename(day, GETDATE()) + '-'
+ datename(year, GETDATE()) + ' '
+ datename(hh, GETDATE()) + ':'
+ datename(mi, GETDATE()) + ':'
+ datename(ss, GETDATE())
THIRD EDIT:
select substring(datename(month, GETDATE()),0,4) + '-'
+ right(datename(day, GETDATE())+100,2) + '-'
+ datename(year, GETDATE()) + ' '
+ right(datename(hh, GETDATE())+100,2) + ':'
+ right(datename(mi, GETDATE())+100,2) + ':'
+ right(datename(ss, GETDATE())+100,2)
The built-in convert won't allow you to format your date exactly as you desire, unfortunately.
With a little manipulation, you can get there though:
SELECT stuff(stuff(convert(VARCHAR(20),GETDATE(),113), 3, 1, '-'), 7, 1, '-')
You could put this in a UDF and call that whenever you want your date formatted in this manner.

Datetime pattern for yyyy.mm.dd.hh.mm.ss pattern code?

What is the DATE FORMAT CODE for "yyyy.mm.dd.hh.mm.ss"?
I know that 34 (date format code) is "yyyymmddhhmmss", but what about the code for "yyyy.mm.dd.hh.mm.ss"?
This is on SQL 2005.
CAST and CONVERT on MSDN says "no".
You have to CONVERT twice with styles 102 and 108, with a concatenation and REPLACE.
Where did you get the "34" date format code from?
As gbn said, using one of the existing formats with some string concatenation would work. Another option is:
SELECT
CAST(YEAR(my_date) AS CHAR(4)) + '.' +
RIGHT('0' + CAST(MONTH(my_date) AS VARCHAR(2)), 2) + '.' +
RIGHT('0' + CAST(DAY(my_date) AS VARCHAR(2)), 2) + '.' +
RIGHT('0' + CAST(DATEPART(HOUR, my_date) AS VARCHAR(2)), 2) + '.' +
RIGHT('0' + CAST(DATEPART(MINUTE, my_date) AS VARCHAR(2)), 2) + '.' +
RIGHT('0' + CAST(DATEPART(SECOND, my_date) AS VARCHAR(2)), 2)
Considering
SELECT CONVERT(VARCHAR(16), GETDATE(), 120) AS [YYYY-MM-DD]
---returns--- yyyy-mm-dd hh:ss
and you can use REPLACE to convert strings
REPLACE('a b c',' ','.')
----returns--- a.b.c
and you can recursively stack things you get to this
Select (
replace((replace((replace(CONVERT(VARCHAR(16), GETDATE(), 120),' ','.')), ':', '.')), '-', '.')
)
which returns: yyyy.mm.dd.hh.ss
works great for datetime stamps or filenames!

How can I find out which data won't cast?

I have a SQL table with a date field defined as char(8), or 20090609, and a time field defined as char(4), or 1230. I am moving this data into another table and I want to combine the two fields and put them in a smalldatetime field in the new table. My query is like this:
INSERT NewTable(eventdate)
SELECT
CAST((datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 3, 2)) as smalldatetime)
FROM OldTable
When I run this, I get an error:
The conversion of char data type to
smalldatetime data type resulted in an
out-of-range smalldatetime value.
I've tried checking len(datecol) and len(timecol) to make sure that they are at least the correct number of characters. I have no idea how I can find the offending data, any suggestions? The database is SQL2000 and I'm using SMO 2008.
Try this:
SELECT datecol, timecol
FROM OldTable
WHERE ISDATE(datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 2, 2)) = 0
That will show you which rows cannot be converted successfully.
It is probably out of the range of acceptable smalldatetime values
January 1, 1900, through June 6, 2079
EDIT On closer inspection I think the substring parameters for the second portion of the time may be incorrect (which may be the whole problem) updated below to reflect substring(timecol, 3, 2)
New Approach this sql does assume that all dates are 8 characters in length, and all times are 4.
Select SubString(DateCol, 1, 4) as tehYear,
Substring(DateCol, 5,2) as tehMonth,
SubString(DateCol, 7,2) as tehDay,
SubString(TimeCol, 1,2) as tehHour,
Substring(TimeCOl, 3,4) as tehMinute,
*
from OldTable
where
(SubString(DateCol, 1,4) > 9999 or SubString(DateCol, 1,4) < 1753)
OR (Substring(DateCol, 5,2) > 12 or Substring(DateCol, 5,2) < 1)
OR (SubString(DateCol, 7,2) > 31 or SubString(DateCol, 7,2) < 1)
OR (SubString(TimeCol, 1,2) > 23 or(SubString(TimeCol, 1,2) < 0)
OR (Substring(TimeCOl, 3,4) > 59 or Substring(TimeCOl, 3,4) <0)
Try casting to datetime and seeing if there are any dates that fall outside of that range to identify your problem data.
SELECT
CAST((datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 3, 2))
as datetime)
FROM OldTable
Where CAST((datecol + ' ' + substring(timecol, 1, 2)
+ ':' + substring(timecol, 3, 2)) as datetime)
> Cast('06/06/2079' as datetime) or CAST((datecol + ' '
+ substring(timecol, 1, 2) + ':' + substring(timecol, 3, 2)) as datetime)
< Cast('01/01/1900' as datetime)
If you run the query in query analyzer it should tell you what row the error occured!