TIMEFROMPARTS() Examples in SQL Server (T-SQL)

The T-SQL TIMEFROMPARTS() function enables you to build a time value from the various time parts. You can also specify the precision of the return value.

Below are examples of how this function works.

Syntax

The syntax goes like this:

TIMEFROMPARTS ( hour, minute, seconds, fractions, precision )

Where the first 4 arguments are integer expressions specifying that particular time part. The 5th argument is an integer literal specifying the precision of the time value to be returned.

Example

Here’s an example to demonstrate.

SELECT TIMEFROMPARTS( 23, 35, 29, 1234567, 7 ) AS Result;

Result:

+------------------+
| Result           |
|------------------|
| 23:35:29.1234567 |
+------------------+

In this case, I specified a precision value of 7.

To be more precise (no pun intended), the precision argument actually specifies the scale. Scale is the number of digits to the right of the decimal point. Precision is the total number of digits.

Invalid Arguments

If any of the arguments are invalid, an error will occur. Example:

SELECT TIMEFROMPARTS( 23, 35, 61, 1234567, 7 ) AS Result;

Result:

Cannot construct data type time, some of the arguments have values which are not valid.

In this case, I provided a minute argument of 61.

Number of Arguments

An error will also occur if you don’t provide the correct number of arguments. Example:

SELECT TIMEFROMPARTS( 23, 35, 29, 7 ) AS Result;

Result:

The timefromparts function requires 5 argument(s).

Null Values

If any of the first 4 arguments are null, the result is NULL:

SELECT TIMEFROMPARTS( 23, 35, NULL, 1234567, 7 ) AS Result;

Result:

+----------+
| Result   |
|----------|
| NULL     |
+----------+

However, if the 5th argument (precision) is null, an error occurs:

SELECT TIMEFROMPARTS( 23, 35, 29, 1234567, NULL ) AS Result;

Result:

Scale argument is not valid. Valid expressions for data type time scale argument are integer constants and integer constant expressions.

Remoting

Microsoft states that the TIMEFROMPARTS() function can be remoted to SQL Server 2012 (11.x) servers and higher. It cannot be remoted to servers that have a version lower than SQL Server 2012 (11.x).

A Similar Function

Also check out SMALLDATETIMEFROMPARTS() Examples in SQL Server (T-SQL) for getting a smalldatetime value instead of a time value.