How do you use the TIMEFROMPARTS function to create a time value from individual hour, minute, and second values?
Posted by RoseHrs
Last Updated: June 02, 2024
The TIMEFROMPARTS function is used in SQL Server to create a TIME data type from individual hour, minute, second, and fractional seconds values. The function takes four parameters: hour, minute, second, and optional fractional seconds, and it returns a time value. Here's the syntax of the TIMEFROMPARTS function:
TIMEFROMPARTS ( hour, minute, second, fractional_seconds, precision )
- hour: The hour component (0-23). - minute: The minute component (0-59). - second: The second component (0-59). - fractional_seconds: The optional fractional seconds (0-999999999). - precision: The optional precision for the fractional seconds. Example Usage: Here is an example of how to use TIMEFROMPARTS to generate a time value:
DECLARE @hour INT = 14;
DECLARE @minute INT = 30;
DECLARE @second INT = 45;

-- Create a TIME value from individual parts
SELECT TIMEFROMPARTS(@hour, @minute, @second, 0, 0) AS TimeValue;
In this example: - We declare three integer variables for hour, minute, and second. - We call TIMEFROMPARTS with those values, adding 0 for both the fractional_seconds and precision, which are optional parameters. - The returned TimeValue will be 14:30:45, which represents 2:30:45 PM. Keep in mind that if any of the input values for hour, minute, or second are out of valid range, it will result in an error.