MS SQL Server

SQL Server Get the Current Time

When working with databases, you often encounter instances where you need to insert the current time. In this post, we will explore the various methods and techniques you can use to fetch the current time in SQL Server.

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:

GETDATE()

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.

select
    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:

current_t|
---------+
 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:

CURRENT_TIMESTAMP

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.

SELECT
    CONVERT(time,
    CURRENT_TIMESTAMP) as current_t;

Running the code above should return the current time as shown:

current_t|
---------+
 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:

SYSDATETIME ( )

The example below demonstrates how to use the sysdatetime() function to get the current time.

SELECT
    SYSDATETIME() as current_t;

Running the query above should return the output:

current_t              |
-----------------------+
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:

SELECT
    CONVERT(time,
    sysdatetime()) as current_t;

Output:

current_t|
---------+
 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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list