DATEADD (Transact-SQL)DATEADD (Transact-SQL)
Aplica-se a:Applies to: SQL ServerSQL Server (todas as versões compatíveis)
SQL ServerSQL Server (all supported versions)
Banco de Dados SQL do AzureAzure SQL Database
Banco de Dados SQL do AzureAzure SQL Database
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Azure Synapse AnalyticsAzure Synapse Analytics
Azure Synapse AnalyticsAzure Synapse Analytics
Parallel Data WarehouseParallel Data Warehouse
Parallel Data WarehouseParallel Data Warehouse
SQL ServerSQL Server (todas as versões compatíveis)
SQL ServerSQL Server (all supported versions)
Banco de Dados SQL do AzureAzure SQL Database
Banco de Dados SQL do AzureAzure SQL Database
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Azure Synapse AnalyticsAzure Synapse Analytics
Azure Synapse AnalyticsAzure Synapse Analytics
Parallel Data WarehouseParallel Data Warehouse
Parallel Data WarehouseParallel Data Warehouse
Essa função adiciona um valor número específico (como um inteiro com sinal) a um datepart especificado de um valor date de entrada e retorna esse valor modificado.This function adds a specified number value (as a signed integer) to a specified datepart of an input date value, and then returns that modified value.
Consulte Tipos de dados e funções de data e hora (Transact-SQL) para obter uma visão geral de todos os tipos de dados e funções de data e hora do Transact-SQLTransact-SQL.See Date and Time Data Types and Functions (Transact-SQL) for an overview of all Transact-SQLTransact-SQL date and time data types and functions.
Convenções da sintaxe Transact-SQL
Transact-SQL Syntax Conventions
SintaxeSyntax
DATEADD (datepart , number , date )
Observação
Para ver a sintaxe do Transact-SQL para o SQL Server 2014 e versões anteriores, confira a Documentação das versões anteriores.To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.
ArgumentosArguments
datepartdatepart
A parte de date à qual o DATEADD
adiciona um número inteiro.The part of date to which DATEADD
adds an integer number. Esta tabela lista todos os argumentos datepart válidos.This table lists all valid datepart arguments.
Observação
DATEADD
não aceita os equivalentes de variável definidos pelo usuário para os argumentos datepart.DATEADD
does not accept user-defined variable equivalents for the datepart arguments.
datepartdatepart | AbreviaçõesAbbreviations |
---|---|
yearyear | yy, yyyyyy, yyyy |
quarterquarter | qq, qqq, q |
monthmonth | mm, mmm, m |
dayofyeardayofyear | dy, ydy, y |
dayday | dd, ddd, d |
weekweek | wk, wwwk, ww |
weekdayweekday | dw, wdw, w |
hourhour | hhhh |
minuteminute | mi, nmi, n |
secondsecond | ss, sss, s |
millisecondmillisecond | msms |
microsecondmicrosecond | mcsmcs |
nanosecondnanosecond | nsns |
numbernumber
Uma expressão que pode ser resolvida para um int que DATEADD
adiciona a um datepart de date.An expression that can resolve to an int that DATEADD
adds to a datepart of date. DATEADD
aceita valores de variável definidos pelo usuário para número.DATEADD
accepts user-defined variable values for number. DATEADD
truncará um valor número especificado que tem uma fração decimal.DATEADD
will truncate a specified number value that has a decimal fraction. Não arrendondará o valor número nessa situação.It will not round the number value in this situation.
datedate
Uma expressão que pode resolver um dos seguintes valores:An expression that can resolve to one of the following values:
- datedate
- datetimedatetime
- datetimeoffsetdatetimeoffset
- datetime2datetime2
- smalldatetimesmalldatetime
- timetime
Para date, DATEADD
aceitará uma variável de expressão de coluna, de expressão, de literal de cadeia de caracteres ou definida pelo usuário.For date, DATEADD
will accept a column expression, expression, string literal, or user-defined variable. Um valor literal de cadeia de caracteres deve resolver um datetime.A string literal value must resolve to a datetime. Para evitar ambiguidade, use anos de quatro dígitos.Use four-digit years to avoid ambiguity issues. Consulte Configurar a opção two digit year cutoff de configuração de servidor para obter informações sobre anos de dois dígitos.See Configure the two digit year cutoff Server Configuration Option for information about two-digit years.
Tipos de retornoReturn types
O tipo de dados do valor retornado para esse método é dinâmico.The return value data type for this method is dynamic. O tipo de retorno depende do argumento fornecido para date
.The return type depends on the argument supplied for date
. Se o valor para date
for uma data literal de cadeia de caracteres, DATEADD
retornará um valor datetime.If the value for date
is a string literal date, DATEADD
returns a datetime value. Se outro tipo de dados de entrada válido for fornecido para date
, DATEADD
retornará o mesmo tipo de dados.If another valid input data type is supplied for date
, DATEADD
returns the same data type. DATEADD
gerará um erro se a escala de segundos do literal de cadeia de caracteres exceder três casas decimais (,nnn) ou se o literal de cadeia de caracteres contiver a parte de deslocamento de fuso horário.DATEADD
raises an error if the string literal seconds scale exceeds three decimal place positions (.nnn) or if the string literal contains the time zone offset part.
Valor retornadoReturn Value
Argumento datepartdatepart Argument
dayofyear, day e weekday retornam o mesmo valor.dayofyear, day, and weekday return the same value.
Cada datepart retorna o mesmo valor das abreviações dela.Each datepart and its abbreviations return the same value.
Se as seguintes condições forem verdadeiras:If the following are true:
- datepart será mêsdatepart is month
- o mês da data terá mais dias do que o mês retornadothe date month has more days than the return month
- o dia da data não existirá no mês retornadothe date day does not exist in the return month
Em seguida, DATEADD
retornará o último dia do mês de retorno.Then, DATEADD
returns the last day of the return month. Por exemplo, setembro tem 30 (trinta) dias; portanto, essas instruções retornam 2006-09-30 00:00:00.000:For example, September has 30 (thirty) days; therefore, these statements return 2006-09-30 00:00:00.000:
SELECT DATEADD(month, 1, '20060830');
SELECT DATEADD(month, 1, '20060831');
Argumento numbernumber Argument
O argumento number não pode exceder o intervalo de int. Nas instruções a seguir, o argumento number excede o intervalo de int em 1.The number argument cannot exceed the range of int. In the following statements, the argument for number exceeds the range of int by 1. Essas instruções retornam a seguinte mensagem de erro: "Msg 8115, Level 16, State 2, Line 1. Arithmetic overflow error converting expression to data type int."
These statements both return the following error message: "Msg 8115, Level 16, State 2, Line 1. Arithmetic overflow error converting expression to data type int."
SELECT DATEADD(year,2147483648, '20060731');
SELECT DATEADD(year,-2147483649, '20060731');
Argumento datedate Argument
DATEADD
não aceitará um argumento date incrementado em um valor fora do intervalo de seu tipo de dados.DATEADD
will not accept a date argument incremented to a value outside the range of its data type. Nas instruções a seguir, o valor number adicionado ao valor de date excede o intervalo do tipo de dados date.In the following statements, the number value added to the date value exceeds the range of the date data type. DATEADD
retorna a seguinte mensagem de erro: "Msg 517, Level 16, State 1, Line 1 Adding a value to a 'datetime' column caused overflow
."DATEADD
returns the following error message: "Msg 517, Level 16, State 1, Line 1 Adding a value to a 'datetime' column caused overflow
."
SELECT DATEADD(year,2147483647, '20060731');
SELECT DATEADD(year,-2147483647, '20060731');
Retorna valores de uma data smalldatetime e uma parte de data de segundo ou frações de segundoReturn Values for a smalldatetime date and a second or Fractional Seconds datepart
A segunda parte de um valor smalldatetime é sempre 00.The seconds part of a smalldatetime value is always 00. Para um valor smalldatetime date, aplica-se o seguinte:For a smalldatetime date value, the following apply:
- Para um datepart de segundo e um valor de número entre -30 e +29,
DATEADD
não fará nenhuma alteração.For a datepart of second, and a number value between -30 and +29,DATEADD
makes no changes. - Para um datepart de segundo e um valor de número menor que -30 ou maior que +29,
DATEADD
executa sua adição a partir do minuto um.For a datepart of second, and a number value less than -30, or more than +29,DATEADD
performs its addition beginning at one minute. - Para um datepart de milissegundos e um valor de número entre -30001 e +29998,
DATEADD
não faça nenhuma alteração.For a datepart of millisecond and a number value between -30001 and +29998,DATEADD
makes no changes. - Para um datepart de milissegundo e um valor de número menor que -30001 ou maior que +29998,
DATEADD
executa sua adição a partir do minuto um.For a datepart of millisecond and a number value less than -30001, or more than +29998,DATEADD
performs its addition beginning at one minute.
ComentáriosRemarks
Use DATEADD
nas seguintes cláusulas:Use DATEADD
in the following clauses:
- GROUP BYGROUP BY
- HAVINGHAVING
- ORDER BYORDER BY
- SELECT <list>SELECT <list>
- WHEREWHERE
Precisão de segundos fracionáriosFractional seconds precision
DATEADD
não permite a adição de um datepart de microssegundo ou nanossegundo para tipos de dados de *date*smalldatetime, date, e datetime.DATEADD
does not allow addition for a datepart of microsecond or nanosecond for date data types smalldatetime, date, and datetime.
Os milissegundos têm uma escala de 3 (0,123). Os microssegundos têm uma escala de 6 (0,123456). Os nanossegundos têm uma escala de 9 (0,123456789).Milliseconds have a scale of 3 (.123), microseconds have a scale of 6 (.123456), and nanoseconds have a scale of 9 (.123456789). Os tipos de dados time, datetime2 e datetimeoffset têm uma escala máxima de 7 (.1234567).The time, datetime2, and datetimeoffset data types have a maximum scale of 7 (.1234567). Para um datepart de nanossegundo, o número deve ser 100 antes do aumento dos segundos fracionários de date.For a datepart of nanosecond, number must be 100 before the fractional seconds of date increase. Um número entre 1 e 49 será arredondado para baixo para 0, e um número de 50 a 99 é arrendondado para cima até 100.A number between 1 and 49 will round down to 0, and a number from 50 to 99 rounds up to 100.
Estas instruções adicionam uma datepart de milissegundo, microssegundo ou nanossegundo.These statements add a datepart of millisecond, microsecond, or nanosecond.
DECLARE @datetime2 datetime2 = '2007-01-01 13:10:10.1111111';
SELECT '1 millisecond', DATEADD(millisecond,1,@datetime2)
UNION ALL
SELECT '2 milliseconds', DATEADD(millisecond,2,@datetime2)
UNION ALL
SELECT '1 microsecond', DATEADD(microsecond,1,@datetime2)
UNION ALL
SELECT '2 microseconds', DATEADD(microsecond,2,@datetime2)
UNION ALL
SELECT '49 nanoseconds', DATEADD(nanosecond,49,@datetime2)
UNION ALL
SELECT '50 nanoseconds', DATEADD(nanosecond,50,@datetime2)
UNION ALL
SELECT '150 nanoseconds', DATEADD(nanosecond,150,@datetime2);
Este é o conjunto de resultados.Here is the result set.
1 millisecond 2007-01-01 13:10:10.1121111
2 milliseconds 2007-01-01 13:10:10.1131111
1 microsecond 2007-01-01 13:10:10.1111121
2 microseconds 2007-01-01 13:10:10.1111131
49 nanoseconds 2007-01-01 13:10:10.1111111
50 nanoseconds 2007-01-01 13:10:10.1111112
150 nanoseconds 2007-01-01 13:10:10.1111113
Deslocamento de fuso horárioTime zone offset
DATEADD
não permite acréscimo ao deslocamento de fuso horário.DATEADD
does not allow addition for time zone offset.
ExemplosExamples
a.A. Incrementando datepart em um intervalo de 1Incrementing datepart by an interval of 1
Cada uma destas instruções incrementa datepart em um intervalo de 1:Each of these statements increments datepart by an interval of 1:
DECLARE @datetime2 datetime2 = '2007-01-01 13:10:10.1111111';
SELECT 'year', DATEADD(year,1,@datetime2)
UNION ALL
SELECT 'quarter',DATEADD(quarter,1,@datetime2)
UNION ALL
SELECT 'month',DATEADD(month,1,@datetime2)
UNION ALL
SELECT 'dayofyear',DATEADD(dayofyear,1,@datetime2)
UNION ALL
SELECT 'day',DATEADD(day,1,@datetime2)
UNION ALL
SELECT 'week',DATEADD(week,1,@datetime2)
UNION ALL
SELECT 'weekday',DATEADD(weekday,1,@datetime2)
UNION ALL
SELECT 'hour',DATEADD(hour,1,@datetime2)
UNION ALL
SELECT 'minute',DATEADD(minute,1,@datetime2)
UNION ALL
SELECT 'second',DATEADD(second,1,@datetime2)
UNION ALL
SELECT 'millisecond',DATEADD(millisecond,1,@datetime2)
UNION ALL
SELECT 'microsecond',DATEADD(microsecond,1,@datetime2)
UNION ALL
SELECT 'nanosecond',DATEADD(nanosecond,1,@datetime2);
Este é o conjunto de resultados.Here is the result set.
Year 2008-01-01 13:10:10.1111111
quarter 2007-04-01 13:10:10.1111111
month 2007-02-01 13:10:10.1111111
dayofyear 2007-01-02 13:10:10.1111111
day 2007-01-02 13:10:10.1111111
week 2007-01-08 13:10:10.1111111
weekday 2007-01-02 13:10:10.1111111
hour 2007-01-01 14:10:10.1111111
minute 2007-01-01 13:11:10.1111111
second 2007-01-01 13:10:11.1111111
millisecond 2007-01-01 13:10:10.1121111
microsecond 2007-01-01 13:10:10.1111121
nanosecond 2007-01-01 13:10:10.1111111
B.B. Incrementando mais de um nível de datepart em uma instruçãoIncrementing more than one level of datepart in one statement
Cada uma destas instruções incrementa datepart em um número grande o suficiente para também incrementar a próxima datepart mais alta de date:Each of these statements increments datepart by a number large enough to additionally increment the next higher datepart of date:
DECLARE @datetime2 datetime2;
SET @datetime2 = '2007-01-01 01:01:01.1111111';
--Statement Result
-------------------------------------------------------------------
SELECT DATEADD(quarter,4,@datetime2); --2008-01-01 01:01:01.1111111
SELECT DATEADD(month,13,@datetime2); --2008-02-01 01:01:01.1111111
SELECT DATEADD(dayofyear,365,@datetime2); --2008-01-01 01:01:01.1111111
SELECT DATEADD(day,365,@datetime2); --2008-01-01 01:01:01.1111111
SELECT DATEADD(week,5,@datetime2); --2007-02-05 01:01:01.1111111
SELECT DATEADD(weekday,31,@datetime2); --2007-02-01 01:01:01.1111111
SELECT DATEADD(hour,23,@datetime2); --2007-01-02 00:01:01.1111111
SELECT DATEADD(minute,59,@datetime2); --2007-01-01 02:00:01.1111111
SELECT DATEADD(second,59,@datetime2); --2007-01-01 01:02:00.1111111
SELECT DATEADD(millisecond,1,@datetime2); --2007-01-01 01:01:01.1121111
C.C. Usando expressões como argumentos para os parâmetros de número e dataUsing expressions as arguments for the number and date parameters
Estes exemplos usam diferentes tipos de expressões como argumentos para os parâmetros number e date.These examples use different types of expressions as arguments for the number and date parameters. Os exemplos usam o banco de dados AdventureWorks.The examples use the AdventureWorks database.
Especificando uma coluna como dataSpecifying a column as date
Este exemplo adiciona 2
(dois) dias a cada valor na coluna OrderDate
para derivar uma nova coluna chamada PromisedShipDate
:This example adds 2
(two) days to each value in the OrderDate
column, to derive a new column named PromisedShipDate
:
SELECT SalesOrderID
,OrderDate
,DATEADD(day,2,OrderDate) AS PromisedShipDate
FROM Sales.SalesOrderHeader;
Um conjunto de resultados parcial:A partial result set:
SalesOrderID OrderDate PromisedShipDate
------------ ----------------------- -----------------------
43659 2005-07-01 00:00:00.000 2005-07-03 00:00:00.000
43660 2005-07-01 00:00:00.000 2005-07-03 00:00:00.000
43661 2005-07-01 00:00:00.000 2005-07-03 00:00:00.000
...
43702 2005-07-02 00:00:00.000 2005-07-04 00:00:00.000
43703 2005-07-02 00:00:00.000 2005-07-04 00:00:00.000
43704 2005-07-02 00:00:00.000 2005-07-04 00:00:00.000
43705 2005-07-02 00:00:00.000 2005-07-04 00:00:00.000
43706 2005-07-03 00:00:00.000 2005-07-05 00:00:00.000
...
43711 2005-07-04 00:00:00.000 2005-07-06 00:00:00.000
43712 2005-07-04 00:00:00.000 2005-07-06 00:00:00.000
...
43740 2005-07-11 00:00:00.000 2005-07-13 00:00:00.000
43741 2005-07-12 00:00:00.000 2005-07-14 00:00:00.000
Especificando variáveis definidas pelo usuário como número e dataSpecifying user-defined variables as number and date
Este exemplo especifica variáveis definidas pelo usuário como argumentos para número e data:This example specifies user-defined variables as arguments for number and date:
DECLARE @days INT = 365,
@datetime DATETIME = '2000-01-01 01:01:01.111'; /* 2000 was a leap year */;
SELECT DATEADD(day, @days, @datetime);
Este é o conjunto de resultados.Here is the result set.
-----------------------
2000-12-31 01:01:01.110
(1 row(s) affected)
Especificando função de sistema escalar como dataSpecifying scalar system function as date
Este exemplo especifica SYSDATETIME
para data.This example specifies SYSDATETIME
for date. O valor exato retornado depende do dia e da hora da execução da instrução:The exact value returned depends on the day and time of statement execution:
SELECT DATEADD(month, 1, SYSDATETIME());
Este é o conjunto de resultados.Here is the result set.
---------------------------
2013-02-06 14:29:59.6727944
(1 row(s) affected)
Especificando subconsultas e funções escalares como número e dataSpecifying scalar subqueries and scalar functions as number and date
Este exemplo usa subconsultas escalares, MAX(ModifiedDate)
, como argumentos para número e data.This example uses scalar subqueries, MAX(ModifiedDate)
, as arguments for number and date. (SELECT TOP 1 BusinessEntityID FROM Person.Person)
funciona como um argumento artificial do parâmetro de número que mostra como selecionar um argumento number em uma lista de valores.(SELECT TOP 1 BusinessEntityID FROM Person.Person)
serves as an artificial argument for the number parameter, to show how to select a number argument from a value list.
SELECT DATEADD(month,(SELECT TOP 1 BusinessEntityID FROM Person.Person),
(SELECT MAX(ModifiedDate) FROM Person.Person));
Especificando expressões numéricas e funções de sistema escalares como número e dataSpecifying numeric expressions and scalar system functions as number and date
Este exemplo usa uma expressão numérica ((10/2))
, operadores unários (-
), um operador aritmético (/
) e funções do sistema escalares (SYSDATETIME
) como argumentos para number e date.This example uses a numeric expression (-(10/2))
, unary operators (-
), an arithmetic operator (/
), and scalar system functions (SYSDATETIME
) as arguments for number and date.
SELECT DATEADD(month,-(10/2), SYSDATETIME());
Especificando funções de classificação como númeroSpecifying ranking functions as number
Este exemplo usa uma função de classificação como um argumento para number.This example uses a ranking function as an argument for number.
SELECT p.FirstName, p.LastName
,DATEADD(day,ROW_NUMBER() OVER (ORDER BY
a.PostalCode),SYSDATETIME()) AS 'Row Number'
FROM Sales.SalesPerson AS s
INNER JOIN Person.Person AS p
ON s.BusinessEntityID = p.BusinessEntityID
INNER JOIN Person.Address AS a
ON a.AddressID = p.BusinessEntityID
WHERE TerritoryID IS NOT NULL
AND SalesYTD <> 0;
Especificando uma função de janela de agregação como númeroSpecifying an aggregate window function as number
Este exemplo usa uma função de janela de agregação como um argumento para number.This example uses an aggregate window function as an argument for number.
SELECT SalesOrderID, ProductID, OrderQty
,DATEADD(day,SUM(OrderQty)
OVER(PARTITION BY SalesOrderID),SYSDATETIME()) AS 'Total'
FROM Sales.SalesOrderDetail
WHERE SalesOrderID IN(43659,43664);
GO
Confira tambémSee also
CAST e CONVERT (Transact-SQL)CAST and CONVERT (Transact-SQL)