Função
Retorna um número correspondente a difereça entre a data/hora de dois valores.
Sintaxe
DATEDIFF ( DatePart , StartDate , EndDate )
Argumentos
DatePart: Especifica em que unidade o resultado será retornado. A tabela a seguir mostra todos os datepart válidos. Valores que não sejam esses não são válidos.
DatePart |
Abreviações |
year |
yy, yyyy |
quarter |
qq, q |
month |
mm, m |
dayofyear |
dy, y |
day |
dd, d |
week |
wk, ww |
hour |
hh |
minute |
mi, n |
second |
ss, s |
millisecond |
ms |
microsecond |
mcs |
nanosecond |
ns |
StartDate: Valor inicial. Pode ser um valor time, date, smalldatetime, datetime, datetime2 ou datetimeoffset, uma expressão, uma expressão de coluna, uma variável definida pelo usuário ou uma cadeia de caracteres. O startdate é subtraído de enddate.
EndDate: Similar so StartDate, porém, representa o valor final, o qual será subtraído por um número.
Tipo de Retorno
int
Exemplos
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate ='2011-06-05'
SET @EndDate ='2011-08-05'
SELECT DATEDIFF(Year, @StartDate, @EndDate) AS NewDate
--Valor retornado = 0 anos
SELECT DATEDIFF(quarter, @StartDate, @EndDate) AS NewDate
--Valor retornado = 1 quarto
SELECT DATEDIFF(Month, @StartDate, @EndDate) AS NewDate
--Valor retornado = 2 meses
SELECT DATEDIFF(dayofyear,@StartDate, @EndDate) AS NewDate
--Valor retornado = 61 dias
SELECT DATEDIFF(Day, @StartDate, @EndDate) AS NewDate
--Valor retornado = 61 dias
SELECT DATEDIFF(Week, @StartDate, @EndDate) AS NewDate
--Valor retornado = 8 semanas
SELECT DATEDIFF(Hour, @StartDate, @EndDate) AS NewDate
-Valor retornado = 1464 horas
SELECT DATEDIFF(minute, @StartDate, @EndDate) AS NewDate
--Valor retornado = 87840 minutos
SELECT DATEDIFF(second, @StartDate, @EndDate) AS NewDate
--Valor retornado = 5270400 segundos
DECLARE @StartDate2 DATETIME
DECLARE @EndDate2 DATETIME
SET @StartDate2 ='2011-06-05'
SET @EndDate2 ='2011-06-06'
SELECT DATEDIFF(millisecond, @StartDate2, @EndDate2) AS NewDate
--Valor retornado = 86400000 milisegundos
Referências
Veja a biblioteca da função DATEDIFF.
Veja Também
SQL Server – TimeStamp
SQL Server – Variáveis Table
_____
Não esqueça de deixar seu comentário, critica, elogio, dúvida e etc. Ele é muito importante para a melhoria do blog.