The DATEDIFF() function returns the time between two dates.
DATEDIFF(datepart,startdate,enddate)
Simple example using Datediff()
SELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS [Difference Date]
Calculating Intervals using Datediff() Function
USE test
CREATE TABLE [dbo].[MyTable](
[CustomerId] [int] NULL,
[DateTime] [datetime] NULL,
[interval] [int] NULL
) ON [PRIMARY]
CREATE PROC CalculateInterval
AS
DECLARE @InsertionTime DATETIME
--SELECT @InsertionTime = [datetime] FROM MyTable WHERE customerid=6
SET @InsertionTime = (SELECT TOP(1) datetime FROM MyTable ORDER BY datetime DESC)
BEGIN
INSERT INTO MyTable(customerid,datetime,Interval)
VALUES(7, GETDATE(), DATEDIFF(SECOND, @InsertionTime, GETDATE()))
END
EXEC CalculateInterval
CREATE TABLE [dbo].[MyTable](
[CustomerId] [int] NULL,
[DateTime] [datetime] NULL,
[interval] [int] NULL
) ON [PRIMARY]
CREATE PROC CalculateInterval
AS
DECLARE @InsertionTime DATETIME
--SELECT @InsertionTime = [datetime] FROM MyTable WHERE customerid=6
SET @InsertionTime = (SELECT TOP(1) datetime FROM MyTable ORDER BY datetime DESC)
BEGIN
INSERT INTO MyTable(customerid,datetime,Interval)
VALUES(7, GETDATE(), DATEDIFF(SECOND, @InsertionTime, GETDATE()))
END
EXEC CalculateInterval
Convert Seconds to hours:minutes:seconds
DECLARE @sec INT
SET @sec=7612
SELECT CONVERT(VARCHAR(5),@sec/3600)+':'+CONVERT(VARCHAR(5),@sec%3600/60)+':'+CONVERT(VARCHAR(5),(@sec%60))
Find total seconds of time in sql server. You can get the Total seconds of the current time in
SELECT [Total Seconds] =
(DATEPART(hh, GETDATE()) * 3600) +
(DATEPART(mi, GETDATE()) * 60) + DATEPART(ss, GETDATE())
References:
time (Transact-SQL) http://msdn.microsoft.com/en-us/library/bb677243.aspxDate and Time Type
http://msdn.microsoft.com/en-us/library/ff848733.aspx
DateDiff()
http://msdn.microsoft.com/en-us/library/aa258269%28v=sql.80%29.aspx
Date and Time Functions
datepart | Abbreviation | ||
---|---|---|---|
year | yy, yyyy | ||
quarter | qq, q | ||
month | mm, m | ||
dayofyear | dy, y | ||
day | dd, d | ||
week | wk, ww | ||
weekday | dw, w | ||
hour | hh | ||
minute | mi, n | ||
second | ss, s | ||
millisecond | ms | ||
microsecond | mcs | ||
nanosecond | ns |
No comments:
Post a Comment