Convert or cast Datetime2 and varchar into datetime - sql-server-2008

I have a date stored as datetime2(7) and a time stored as varchar(5).
e.g.
Date = 2016-11-30 00:00:00.000000 (datetime2)
Time = 09:00 (varchar)
Output should be 2016-11-30 09:00:00.000000 (datetime).
How do I convert or cast these as a datetime. I have tried several ways but have been unsuccessful.
Thank you in advance for your help.

Maybe simple as this?
DECLARE #d DATETIME2(7)='2016-11-30 00:00:00.000000'
DECLARE #t VARCHAR(5)='09:00';
SELECT CAST(CAST(#d AS DATETIME) + CAST(#t+':00' AS DATETIME) AS datetime2(7))
Your time needs just :00 to it, than you can cast this to DATETIME. Two values of type DATETIMEcan be added.
The whole expression can be re-converted to DATETIME2.

How about something like this:
DECLARE #MYDATE DATETIME2;
DECLARE #MYTIME VARCHAR(5);
SET #MYDATE = '2016-11-30'; -- this is equal to 2016-11-30 00:00:00.000000
SET #MYTIME = '09:00';
-- for datetime2
SELECT CAST(CAST(LEFT(#MYDATE,10) AS VARCHAR) + ' ' + #MYTIME + ':00.000000' AS DATETIME2)
-- for datetime
SELECT CONVERT(DATETIME,CAST(LEFT(#MYDATE,10) AS VARCHAR) + ' ' + #MYTIME + ':00') -- for datetime

Related

convert varchar to date in sql

I have a column where date is stored as Sep-19,Nov-13,Aug-19 which is in varchar type i have to convert it to date type
SELECT CONVERT(Datetime, '2011-09-28 18:01:00', 120) -- to convert it to Datetime
SELECT CONVERT( VARCHAR(30), #date ,105) -- italian format [28-09-2011 18:01:00]
+ ' ' + SELECT CONVERT( VARCHAR(30), #date ,108 ) -- full date [with time/minutes/sec]

SQL Server 2008 Datetime conversion

Looking to convert datetime format
20150416 12:29:20:845
to
20150416 12:29:20:84.
I have tried a number of date time conversion but no luck.
DECLARE #Date varchar(22)
SET #Date = CONVERT(Varchar(23), GETDATE(),121) --replace getdate with your value
SELECT #DATE --2015-04-17 10:56:55.29 format you need
SELECT GETDATE() --2015-04-17 10:56:55.297 actual value
SELECT CAST(#DATE as datetime) --2015-04-17 10:56:55.290 if u convert it back
Assuming that you already converted your date as varchar, you can use this query:
DECLARE #V VARCHAR(30) = '20150416 12:29:20:845'
SELECT LEFT(#V,20),STUFF(#V,21,1,'.')

Date Wise Report in SQL server 2008

How to get following output ?
[1],[2],[3],[4],[5],[6],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17]
,[18],[19],[20]
,[21],[22],[23],[24],[25],[26],[27],[28],[29],[30]
Need to fetch all dates from given month in sql server
I want to display daily Date Wise report
Example :
If I pass date as '11/01/2012' then it should return above result
and if I pass December than 31 days.
Very unclear question but try
DECLARE #epoch DATETIME = '20130101'
;WITH cte AS
(
SELECT #epoch DateKey
UNION ALL
SELECT DATEADD(D, 1, DateKey)
FROM cte
WHERE MONTH(DATEADD(D, 1, DateKey))=MONTH(#epoch)
)
SELECT * FROM cte
try below code
declare #date datetime = '09/10/2012'
declare #noofdays int
select #noofdays =datediff(day, #date, dateadd(month, 1, #date))
DECLARE #startDate DATETIME=CAST(MONTH(#date) AS VARCHAR) + '/' + '01/' + + CAST(YEAR(#date) AS VARCHAR) -- mm/dd/yyyy
DECLARE #endDate DATETIME= CAST(MONTH(#date) AS VARCHAR) + '/' + cast(#noofdays as varchar) + '/' + CAST(YEAR(#date) AS VARCHAR)
;WITH Calender AS
(
SELECT #startDate AS CalanderDate
UNION ALL
SELECT CalanderDate + 1 FROM Calender
WHERE CalanderDate + 1 <= #endDate
)
SELECT [Date] = CONVERT(VARCHAR(10),CalanderDate,25)
FROM Calender
OPTION (MAXRECURSION 0)
I am able to find out answer my self....
Thanks Buddy for trying to help me...
DECLARE #COLSPIVOT AS NVARCHAR(MAX)=''
declare #MaxDate int
set #MaxDate=(SELECT day(DATEADD(ms,-2,DATEADD(MONTH, DATEDIFF(MONTH,0,'8/1/2013')+1,0)))
AS [Current Month])
declare #i int =1
while (#i<=#MaxDate)
begin
set #COLSPIVOT=#COLSPIVOT+'['+convert(varchar(10),#i)+']'
if(#i!=#MaxDate)
begin
set #COLSPIVOT=#COLSPIVOT+','
end
set #i=#i+1
end
select #COLSPIVOT

convert int to date to add a dayn and convert to int back

I have int value with YYYYMM. I want to:
1. convert it into datetime
2. add one day DATEADD(Day, +1, #date)
3. convert it back into int
What's the easiest way to do this?
Here is a nice exercise and I hope it works out for you...
declare #date date
declare #newDate date
set #date = convert(date, '20100101')
set #newdate = DateAdd(dd, 1, #Date)
select #date
select #newdate
select convert(int, convert(varchar, #newdate, 112)) -- this is your final conversion back to int
If your initial int is, say, 201310 (October 2013), then what I think you want is this:
select convert(datetime, rtrim(201310 * 100 + 1))
The function RTRIM is a trick to convert int to string type.
The result is this:
2013-10-01 00:00:00.000
If you don't want to use RTRIM, the command below will get you the same result:
select convert(datetime, convert(char, 201310 * 100 + 1))

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

I have a SQL Server table that has a "Time" column. The table is a log table the houses status messages and timestamps for each message. The log table is inserted into via a batch file. There is an ID column that groups rows together. Each time the batch file runs it initializes the ID and writes records. What I need to do is get the elapsed time from the first record in an ID set to the last record of the same ID set. I started toying with select Max(Time) - Min(Time) from logTable where id = but couldn't figure out how to format it correctly. I need it in HH:MM:SS.
SQL Server doesn't support the SQL standard interval data type. Your best bet is to calculate the difference in seconds, and use a function to format the result. The native function CONVERT() might appear to work fine as long as your interval is less than 24 hours. But CONVERT() isn't a good solution for this.
create table test (
id integer not null,
ts datetime not null
);
insert into test values (1, '2012-01-01 08:00');
insert into test values (1, '2012-01-01 09:00');
insert into test values (1, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 10:30');
insert into test values (2, '2012-01-01 09:00');
insert into test values (3, '2012-01-01 09:00');
insert into test values (3, '2012-01-02 12:00');
Values were chosen in such a way that for
id = 1, elapsed time is 1 hour
id = 2, elapsed time is 2 hours, and
id = 3, elapsed time is 3 hours.
This SELECT statement includes one column that calculates seconds, and one that uses CONVERT() with subtraction.
select t.id,
min(ts) start_time,
max(ts) end_time,
datediff(second, min(ts),max(ts)) elapsed_sec,
convert(varchar, max(ts) - min(ts), 108) do_not_use
from test t
group by t.id;
ID START_TIME END_TIME ELAPSED_SEC DO_NOT_USE
1 January, 01 2012 08:00:00 January, 01 2012 09:00:00 3600 01:00:00
2 January, 01 2012 08:30:00 January, 01 2012 10:30:00 7200 02:00:00
3 January, 01 2012 09:00:00 January, 02 2012 12:00:00 97200 03:00:00
Note the misleading "03:00:00" for the 27-hour difference on id number 3.
Function to format elapsed time in SQL Server
UPDATED:
Correctly calculate a timespan in SQL Server, even if more than 24 hours:
-- Setup test data
declare #minDate datetime = '2012-12-12 20:16:47.160'
declare #maxDate datetime = '2012-12-13 15:10:12.050'
-- Get timespan in hh:mi:ss
select cast(
(cast(cast(#maxDate as float) - cast(#minDate as float) as int) * 24) /* hours over 24 */
+ datepart(hh, #maxDate - #minDate) /* hours */
as varchar(10))
+ ':' + right('0' + cast(datepart(mi, #maxDate - #minDate) as varchar(2)), 2) /* minutes */
+ ':' + right('0' + cast(datepart(ss, #maxDate - #minDate) as varchar(2)), 2) /* seconds */
-- Returns 18:53:24
Edge cases that show inaccuracy are especially welcome!
DECLARE #EndTime AS DATETIME, #StartTime AS DATETIME
SELECT #StartTime = '2013-03-08 08:00:00', #EndTime = '2013-03-08 08:30:00'
SELECT CAST(#EndTime - #StartTime AS TIME)
Result: 00:30:00.0000000
Format result as you see fit.
The best and simple way:
Convert(varchar, {EndTime} - {StartTime}, 108)
Just like Anri noted.
Use the DATEDIFF to return value in milliseconds, seconds, minutes, hours, ...
DATEDIFF(interval, date1, date2)
interval REQUIRED - The time/date part to return. Can be one of the following values:
year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear = Day of the year
day, dy, y = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond
date1, date2 REQUIRED - The two dates to calculate the difference between
select convert(varchar, Max(Time) - Min(Time) , 108) from logTable where id=...
See if this helps. I can set variables for Elapsed Days, Hours, Minutes, Seconds.
You can format this to your liking or include in a user defined function.
Note: Don't use DateDiff(hh,#Date1,#Date2). It is not reliable! It rounds in unpredictable ways
Given two dates...
(Sample Dates: two days, three hours, 10 minutes, 30 seconds difference)
declare #Date1 datetime = '2013-03-08 08:00:00'
declare #Date2 datetime = '2013-03-10 11:10:30'
declare #Days decimal
declare #Hours decimal
declare #Minutes decimal
declare #Seconds decimal
select #Days = DATEDIFF(ss,#Date1,#Date2)/60/60/24 --Days
declare #RemainderDate as datetime = #Date2 - #Days
select #Hours = datediff(ss, #Date1, #RemainderDate)/60/60 --Hours
set #RemainderDate = #RemainderDate - (#Hours/24.0)
select #Minutes = datediff(ss, #Date1, #RemainderDate)/60 --Minutes
set #RemainderDate = #RemainderDate - (#Minutes/24.0/60)
select #Seconds = DATEDIFF(SS, #Date1, #RemainderDate)
select #Days as ElapsedDays, #Hours as ElapsedHours, #Minutes as ElapsedMinutes, #Seconds as ElapsedSeconds
Hope this helps you in getting the exact time between two time stamps
Create PROC TimeDurationbetween2times(#iTime as time,#oTime as time)
As
Begin
DECLARE #Dh int, #Dm int, #Ds int ,#Im int, #Om int, #Is int,#Os int
SET #Im=DATEPART(MI,#iTime)
SET #Om=DATEPART(MI,#oTime)
SET #Is=DATEPART(SS,#iTime)
SET #Os=DATEPART(SS,#oTime)
SET #Dh=DATEDIFF(hh,#iTime,#oTime)
SET #Dm = DATEDIFF(mi,#iTime,#oTime)
SET #Ds = DATEDIFF(ss,#iTime,#oTime)
DECLARE #HH as int, #MI as int, #SS as int
if(#Im>#Om)
begin
SET #Dh=#Dh-1
end
if(#Is>#Os)
begin
SET #Dm=#Dm-1
end
SET #HH = #Dh
SET #MI = #Dm-(60*#HH)
SET #SS = #Ds-(60*#Dm)
DECLARE #hrsWkd as varchar(8)
SET #hrsWkd = cast(#HH as char(2))+':'+cast(#MI as char(2))+':'+cast(#SS as char(2))
select #hrsWkd as TimeDuration
End