SQL Server Get the Current Time
Method 1 – Using SQL Server GETDATE() Function
The most basic method of fetching the current time in SQL Server is using the GETDATE() function. This function returns the current date and time from the host system.
The function syntax is as shown below:
The function returns the date and time as a datetime type.
The example below illustrates the GETDATE() function to get the current date and time.
CONVERT(time,
GETDATE()) as current_t;
Once we run the query above, SQL Server should return the current time from the host system. An example output is displayed below:
---------+
08:02:40|
Method 2 – Using SQL Server CURRENT_TIMESTAMP() Function
The second method we can use to fetch the current time in SQL Server is the current_timestamp() function. This function is part of Standard SQL and acts as an alias to the getdate() function.
The syntax is as shown:
Similarly, the function does not accept arguments and returns a datetime data type. The following example shows how to fetch the current time using the current_timestamp() function.
CONVERT(time,
CURRENT_TIMESTAMP) as current_t;
Running the code above should return the current time as shown:
---------+
08:11:51|
Method 3 – Using Sysdatetime() Function
SQL Server also provides us with the SYSDATETIME() function, which we can use to get the current time from the host system.
The function syntax is as shown:
The example below demonstrates how to use the sysdatetime() function to get the current time.
SYSDATETIME() as current_t;
Running the query above should return the output:
-----------------------+
2022-10-17 08:48:45.127|
In this case, we can see a more precise output than the GETDATE() Function.
Similarly, we can convert the output from the sysdatetime() function to get only the date or time value.
The code is as shown:
CONVERT(time,
sysdatetime()) as current_t;
Output:
---------+
08:51:40|
Conclusion
This post explored various functions we can use in SQL Server to fetch the current time. We hope you enjoyed this post.
Source: linuxhint.com