T-SQL DATETIME2FROMPARTS() Function
The T-SQL (Transact-SQL) DATETIME2FROMPARTS() function returns a datetime value from the specified date and time arguments with specified precision.
The DATETIME2FROMPARTS() function returns NULL if any of the argument has a null value. However, if the precision argument is null, then an error is raised. For invalid arguments, an error will be raised.
The fractions argument depends on the precision argument. For example, if precision is 7, then each fraction represents 100 nanoseconds; if precision is 3, then each fraction represents a millisecond. If the value of precision is zero, then the value of fractions must also be zero; otherwise, an error is raised.
Syntax
DATETIME2FROMPARTS(year, month, day, hour, minute, seconds, fractions, precision)
Parameters
year |
Required. Specify the year of the datetime value. |
month |
Required. Specify the month of the datetime value. |
day |
Required. Specify the day of the datetime value. |
hour |
Required. Specify the hours of the datetime value. |
minute |
Required. Specify the minutes of the datetime value. |
seconds |
Required. Specify the seconds of the datetime value. |
fractions |
Required. Specify the fraction of the datetime value. |
precision |
Required. Specify the precision of the datetime value to be returned. |
Return Value
Returns the datetime value from the specified parts.
Example 1:
The example below shows the usage of DATETIME2FROMPARTS() function.
SELECT DATETIME2FROMPARTS(1999, 10, 25, 22, 45, 58, 0, 0); Result: '1999-10-25 22:45:58.0000000' SELECT DATETIME2FROMPARTS(1999, 10, 25, 22, 45, 58, 4, 1); Result: '1999-10-25 22:45:58.4' SELECT DATETIME2FROMPARTS(1999, 10, 25, 22, 45, 58, 40, 2); Result: '1999-10-25 22:45:58.40' SELECT DATETIME2FROMPARTS(1999, 10, 25, 22, 45, 58, 400, 3); Result: '1999-10-25 22:45:58.400'
Example 2:
Consider a database table called DateTimeTable with the following records:
ID | Year | Month | Day | Hours | Minutes | Seconds |
---|---|---|---|---|---|---|
1 | 1999 | 3 | 23 | 22 | 45 | 55 |
2 | 2003 | 6 | 8 | 5 | 34 | 21 |
3 | 2010 | 11 | 28 | 14 | 23 | 10 |
4 | 2004 | 8 | 14 | 9 | 8 | 19 |
5 | 2012 | 1 | 18 | 8 | 11 | 18 |
The following statement can be used to get the datetime value using the records of various columns of this table.
SELECT *, DATETIME2FROMPARTS(Year, Month, Day, Hours, Minutes, Seconds, 0, 3) AS DATETIME2FROMPARTS_Value FROM DateTimeTable;
This will produce the result as shown below:
ID | Year | Month | Day | Hours | Minutes | Seconds | DATETIME2FROMPARTS_Value |
---|---|---|---|---|---|---|---|
1 | 1999 | 3 | 23 | 22 | 45 | 55 | 1999-03-23 22:45:55.000 |
2 | 2003 | 6 | 8 | 5 | 34 | 21 | 2003-06-08 05:34:21.000 |
3 | 2010 | 11 | 28 | 14 | 23 | 10 | 2010-11-28 14:23:10.000 |
4 | 2004 | 8 | 14 | 9 | 8 | 19 | 2004-08-14 09:08:19.000 |
5 | 2012 | 1 | 18 | 8 | 11 | 18 | 2012-01-18 08:11:18.000 |
❮ T-SQL Functions