Search This Blog

Wednesday, August 22, 2012

How can calculate date difference DATEDIFF (Transact-SQL)


DATEDIFF (Transact-SQL)

DATEDIFF ( datepart , startdate , enddate )
You can use SQL Server DateDiff function to calculate difference between two dates. This delay can be calculated in days, months, years, minutes,hours or seconds.

Sno
Datepart
Abbreviations
1
year
yy, yyyy
2
quarter
qq, q
3
month
mm, m
4
dayofyear 
dy, y
5
day
dd, d
6
week
wk, ww
7
Hour
hh
8
minute
mi, n
9
second
ss, s
10
millisecond
ms


 Table Detail: (table name Row_Number)

Fname
Salary
State
Todate
Fromdate
Vipin
 10000
Delhi   
 2001-12-01 00:00:00.000
2002-12-01 00:00:00.000
Chandra
 9000
Delhi   
 2003-12-03 00:00:00.000
2019-12-21 00:00:00.000
Taslim
 8000
UP
 2003-12-03 01:12:34.347
2003-12-05 07:44:46.110
Raghu
 12000
UP
 2003-12-05 07:44:46.110
2006-12-05 07:44:46.110
1.select * from Row_Number
SELECT DATEDIFF(yyyy, "Todate","Fromdate")as yearDiffrence from Row_Number
Output:
yearDiffrence
1
16
0
3

2.SELECT DATEDIFF(qq, "Todate","Fromdate")as quarter from Row_Number
Output:
quarter
4
64
0
12

3.SELECT DATEDIFF(mm, "Todate","Fromdate")as month from Row_Number
Output:
month
12
192
0
36

4.SELECT DATEDIFF(dy, "Todate","Fromdate")as dayofyear from Row_Number
Output:
dayofyear
365
5862
2
1096

5.SELECT DATEDIFF(dd, "Todate","Fromdate")as day from Row_Number
Output:
day
365
5862
2
1096

6.SELECT DATEDIFF(wk, "Todate","Fromdate")as week from Row_Number
Output:
week
53
837
0
157

7.SELECT DATEDIFF(hh, "Todate","Fromdate")as Hour from Row_Number
Output:
Hour
8760
140688
54
26304

8.SELECT DATEDIFF(mi, "Todate","Fromdate")as minute from Row_Number
Output:
minute
525600
8441280
3272
1578240

9.SELECT DATEDIFF(ss, "Todate","Fromdate")as second from Row_Number
Output:
second
31536000
506476800
196332
94694400

10.SELECT DATEDIFF(ms, "Todate","Fromdate")as millisecond from Row_Number

No comments :