DATEDIFF_BIG (Transact-SQL)DATEDIFF_BIG (Transact-SQL)
Si applica a:Applies to: SQL Server 2016 (13.x)SQL Server 2016 (13.x)
SQL Server 2016 (13.x)SQL Server 2016 (13.x)
database SQL di AzureAzure SQL Database
database SQL di AzureAzure SQL Database
Istanza gestita di SQL di AzureAzure SQL Managed Instance
Istanza gestita di SQL di AzureAzure SQL Managed Instance
SQL Server 2016 (13.x)SQL Server 2016 (13.x)
SQL Server 2016 (13.x)SQL Server 2016 (13.x)
database SQL di AzureAzure SQL Database
database SQL di AzureAzure SQL Database
Istanza gestita di SQL di AzureAzure SQL Managed Instance
Istanza gestita di SQL di AzureAzure SQL Managed Instance
Questa funzione restituisce il numero (sotto forma di valore big integer con segno) di limiti di datepart specificati sovrapposti tra gli elementi startdate ed enddate indicati.This function returns the count (as a signed big integer value) of the specified datepart boundaries crossed between the specified startdate and enddate.
Vedere Funzioni e tipi di dati di data e ora (Transact-SQL) per una panoramica di tutti i tipi di dati e delle funzioni di data e ora di 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.
Convenzioni della sintassi Transact-SQL
Transact-SQL Syntax Conventions
SintassiSyntax
DATEDIFF_BIG ( datepart , startdate , enddate )
ArgomentiArguments
datepartdatepart
Parte di startdate ed enddate che specifica il tipo di limite superato.The part of startdate and enddate that specifies the type of boundary crossed.
Nota
DATEDIFF_BIG
non accetta valori datepart da variabili definite dall'utente o come stringhe tra virgolette.DATEDIFF_BIG
will not accept datepart values from user-defined variables or as quoted strings.
Questa tabella elenca i nomi e le abbreviazioni di tutti gli argomenti datepart validi.This table lists all valid datepart argument names and abbreviations.
Nome datepartdatepart name | Abbreviazione datepartdatepart abbreviation |
---|---|
yearyear | yy, yyyyyy, yyyy |
quarterquarter | qq, qqq, q |
monthmonth | mm, mmm, m |
dayofyeardayofyear | dy, ydy, y |
dayday | dd, ddd, d |
weekweek | wk, wwwk, ww |
hourhour | hhhh |
minuteminute | mi, nmi, n |
secondsecond | ss, sss, s |
millisecondmillisecond | msms |
microsecondmicrosecond | mcsmcs |
nanosecondnanosecond | nsns |
Nota
Ogni nome datepart specifico e le abbreviazioni datepart corrispondenti restituiscono lo stesso valore.Each specific datepart name and abbreviations for that datepart name will return the same value.
startdatestartdate
Espressione che può risolversi in uno dei valori seguenti:An expression that can resolve to one of the following values:
- datedate
- datetimedatetime
- datetimeoffsetdatetimeoffset
- datetime2datetime2
- smalldatetimesmalldatetime
- timetime
Per date, DATEDIFF_BIG
accetta un'espressione di colonna, un'espressione, un valore letterale stringa o una variabile definita dall'utente.For date, DATEDIFF_BIG
will accept a column expression, expression, string literal, or user-defined variable. Un valore stringa deve risolversi in un elemento datetime.A string literal value must resolve to a datetime. Per evitare problemi di ambiguità, esprimere gli anni nel formato a quattro cifre.Use four-digit years to avoid ambiguity issues. DATEDIFF_BIG
sottrae startdate da enddate.DATEDIFF_BIG
subtracts startdate from enddate. Per evitare ambiguità, esprimere gli anni nel formato a quattro cifre.To avoid ambiguity, use four-digit years. Per informazioni sugli anni a due cifre, vedere Configurare l'opzione di configurazione del server Cambio data per anno a due cifre.See Configure the two digit year cutoff Server Configuration Option for information about two-digit years.
enddateenddate
Vedere startdate.See startdate.
Tipo restituitoReturn Type
bigint con segnoSigned bigint
Valore restituitoReturn Value
Restituisce la differenza bigint tra startdate ed enddate, espressa nel limite impostato da datepart.Returns the bigint difference between the startdate and enddate, expressed in the boundary set by datepart.
Per un valore restituito esterno all'intervallo per bigint (da -9.223.372.036.854.775.808 a +9.223.372.036.854.775.807), DATEDIFF_BIG
restituisce un errore.For a return value out of range for bigint (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807), DATEDIFF_BIG
returns an error. A differenza di che restituisce un int e può quindi determinare un overflow con una precisione di minute o superiore, DATEDIFF_BIG
può determinare un overflow solo se si usa la precisione nanosecond dove la differenza tra enddate e startdate è superiore a 292 anni, 3 mesi, 10 giorni, 23 ore, 47 minuti e 16.8547758 secondi.Unlike , which returns an int and therefore may overflow a minute or higher, DATEDIFF_BIG
can only overflow if using nanosecond precision where the difference between enddate and startdate is more than 292 years, 3 months, 10 days, 23 hours, 47 minutes, and 16.8547758 seconds.
Se sia a startdate che a enddate è stato assegnato solo un valore orario e datepart non è un datepart orario, DATEDIFF_BIG
restituisce 0.If startdate and enddate are both assigned only a time value, and the datepart isn't a time datepart, DATEDIFF_BIG
returns 0.
Per calcolare il valore restituito, DATEDIFF_BIG
usa un componente differenza di fuso orario startdate o enddate.DATEDIFF_BIG
does use a time zone offset component of startdate or enddate to calculate the return value.
Per un valore smalldatetime usato per startdate o enddate, nel valore restituito DATEDIFF_BIG
imposta sempre i secondi e i millisecondi su 0, perché smalldatetime garantisce la precisione solo a livello di minuti.For a smalldatetime value used for startdate or enddate, DATEDIFF_BIG
always sets seconds and milliseconds to 0 in the return value because smalldatetime only has accuracy to the minute.
Se a una variabile di tipo data viene assegnato solo il valore dell'ora, DATEDIFF_BIG
imposta il valore della parte mancante della data sul valore predefinito: 1900-01-01
.If only a time value is assigned to a date data type variable, DATEDIFF_BIG
sets the value of the missing date part to the default value: 1900-01-01
. Se a una variabile di tipo ora o data viene assegnato solo il valore della data, DATEDIFF_BIG
imposta il valore della parte mancante dell'ora sul valore predefinito: 00:00:00
.If only a date value is assigned to a variable of a time or date data type, DATEDIFF_BIG
sets the value of the missing time part to the default value: 00:00:00
. Se startdate ed enddate hanno rispettivamente solo la parte relativa all'ora o solo la parte relativa alla data, DATEDIFF_BIG
imposta le parti mancanti sui rispettivi valori predefiniti.If either startdate or enddate have only a time part and the other only a date part, DATEDIFF_BIG
sets the missing time and date parts to the default values.
Se i valori startdate ed enddate sono di tipi data diversi e uno di questi comprende un numero maggiore di parti di ora o offre una precisione in secondi frazionari maggiore, DATEDIFF_BIG
imposta le parti mancanti dell'altro valore su 0.If startdate and enddate have different date data types, and one has more time parts or fractional seconds precision than the other, DATEDIFF_BIG
sets the missing parts of the other to 0.
Limiti di datepartdatepart boundaries
Le istruzioni seguenti hanno gli stessi valori startdate ed enddate.The following statements have the same startdate and the same enddate values. Queste date sono adiacenti e differiscono di un microsecondo (0,0000001 secondi).Those dates are adjacent and they differ in time by one microsecond (.0000001 second). La differenza tra startdate e enddate in ogni istruzione oltrepassa un limite di calendario o di ora del rispettivo valore datepart.The difference between the startdate and enddate in each statement crosses one calendar or time boundary of its datepart. Ciascuna istruzione restituisce 1.Each statement returns 1. Se startdate ed enddate hanno valori di anno diversi, ma gli stessi valori di settimana di calendario, DATEDIFF_BIG
restituirà 0 per datepart week.If startdate and enddate have different year values but they have the same calendar week values, DATEDIFF_BIG
will return 0 for datepart week.
SELECT DATEDIFF_BIG(year, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(quarter, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(month, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(dayofyear, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(day, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(week, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(hour, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(minute, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(second, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
OsservazioniRemarks
Usare DATEDIFF_BIG
nelle clausole SELECT <list>
, WHERE
, HAVING
, GROUP BY
e ORDER BY
.Use DATEDIFF_BIG
in the SELECT <list>
, WHERE
, HAVING
, GROUP BY
and ORDER BY
clauses.
DATEDIFF_BIG
consente di eseguire in modo implicito il cast di valori letterali stringa come tipo di dati datetime2.DATEDIFF_BIG
implicitly casts string literals as a datetime2 type. DATEDIFF_BIG
, pertanto, non supporta il formato AGM se la data viene passata come stringa.This means that DATEDIFF_BIG
doesn't support the format YDM when the date is passed as a string. Per usare il formato AGM è necessario eseguire il cast della stringa in modo esplicito in un tipo datetime o smalldatetime.You must explicitly cast the string to a datetime or smalldatetime type to use the YDM format.
La specifica di SET DATEFIRST
non ha alcun effetto su DATEDIFF_BIG
.Specifying SET DATEFIRST
has no effect on DATEDIFF_BIG
. DATEDIFF_BIG
usa sempre la domenica come primo giorno della settimana, per garantire che la funzione operi in modo deterministico.DATEDIFF_BIG
always uses Sunday as the first day of the week to ensure the function operates in a deterministic way.
DATEDIFF_BIG
può determinare un overflow con nanosecond se la differenza tra enddate e startdate restituisce un valore non compreso nell'intervallo per bigint.DATEDIFF_BIG
may overflow with a nanosecond if the difference between enddate and startdate returns a value that is out of range for bigint.
EsempiExamples
Specifica di colonne per startdate ed enddateSpecifying columns for startdate and enddate
Questo esempio, che usa tipi diversi di espressioni come argomenti per i parametri startdate ed enddate,This example uses different types of expressions as arguments for the startdate and enddate parameters. calcola il numero di limiti di giorno sovrapposti tra le date di due colonne di una tabella.It calculates the number of day boundaries crossed between dates in two columns of a table.
CREATE TABLE dbo.Duration
(startDate datetime2, endDate datetime2);
INSERT INTO dbo.Duration(startDate,endDate)
VALUES('2007-05-06 12:10:09', '2007-05-07 12:10:09');
SELECT DATEDIFF_BIG(day, startDate, endDate) AS 'Duration'
FROM dbo.Duration;
-- Returns: 1
Ricerca della differenza tra startdate e enddate come stringhe di parti di dataFinding difference between startdate and enddate as date parts strings
DECLARE @date1 DATETIME2, @date2 DATETIME2, @result VARCHAR(100)
DECLARE @years BIGINT, @months BIGINT, @days BIGINT, @hours BIGINT, @minutes BIGINT, @seconds BIGINT, @milliseconds BIGINT
SET @date1 = '0001-01-01 00:00:00.00000000'
SET @date2 = '2018-12-12 07:08:01.12345678'
SELECT @years = DATEDIFF(yy, @date1, @date2)
IF DATEADD(yy, -@years, @date2) < @date1
SELECT @years = @years-1
SET @date2 = DATEADD(yy, -@years, @date2)
SELECT @months = DATEDIFF(mm, @date1, @date2)
IF DATEADD(mm, -@months, @date2) < @date1
SELECT @months=@months-1
SET @date2= DATEADD(mm, -@months, @date2)
SELECT @days=DATEDIFF(dd, @date1, @date2)
IF DATEADD(dd, -@days, @date2) < @date1
SELECT @days=@days-1
SET @date2= DATEADD(dd, -@days, @date2)
SELECT @hours=DATEDIFF(hh, @date1, @date2)
IF DATEADD(hh, -@hours, @date2) < @date1
SELECT @hours=@hours-1
SET @date2= DATEADD(hh, -@hours, @date2)
SELECT @minutes=DATEDIFF(mi, @date1, @date2)
IF DATEADD(mi, -@minutes, @date2) < @date1
SELECT @minutes=@minutes-1
SET @date2= DATEADD(mi, -@minutes, @date2)
SELECT @seconds=DATEDIFF(s, @date1, @date2)
IF DATEADD(s, -@seconds, @date2) < @date1
SELECT @seconds=@seconds-1
SET @date2= DATEADD(s, -@seconds, @date2)
SELECT @milliseconds=DATEDIFF(ms, @date1, @date2)
SELECT @result= ISNULL(CAST(NULLIF(@years,0) AS VARCHAR(10)) + ' years,','')
+ ISNULL(' ' + CAST(NULLIF(@months,0) AS VARCHAR(10)) + ' months,','')
+ ISNULL(' ' + CAST(NULLIF(@days,0) AS VARCHAR(10)) + ' days,','')
+ ISNULL(' ' + CAST(NULLIF(@hours,0) AS VARCHAR(10)) + ' hours,','')
+ ISNULL(' ' + CAST(@minutes AS VARCHAR(10)) + ' minutes and','')
+ ISNULL(' ' + CAST(@seconds AS VARCHAR(10))
+ CASE WHEN @milliseconds > 0 THEN '.' + CAST(@milliseconds AS VARCHAR(10))
ELSE '' END
+ ' seconds','')
SELECT @result
Questo è il set di risultati.Here is the result set.
2017 years, 11 months, 11 days, 7 hours, 8 minutes and 1.123 seconds
Per esempi più strettamente correlati, vedere DATEDIFF (Transact-SQL).See more closely related examples in DATEDIFF (Transact-SQL).
Vedere ancheSee also
CAST e CONVERT (Transact-SQL)CAST and CONVERT (Transact-SQL)
DATEDIFF (Transact-SQL)DATEDIFF (Transact-SQL)