How to print GETDATE() in SQL Server with milliseconds in time?
For quick millisecond precision in SQL Server, use the FORMAT
function as follows:
This wraps the GETDATE()
function with FORMAT
, employing the 'yyyy-MM-dd HH:mm:ss.fff'
format string, capturing milliseconds (fff
) along with the more standard date-time elements.
Enhancing precision
Using SYSDATETIME()
over GETDATE()
provides a higher level of precision. You can convert and format the current timestamp to include milliseconds as follows:
Increasing precision adds just enough spice to keep things interesting!
Navigate the PRINT roadblock
The PRINT
statement won't show milliseconds as is. Instead of a detour, let's use SELECT
with our conversion techniques:
Fun fact: SQL statements love a chat, especially when it's precise!
Making smart datatype choices
When storing time values of high precision, use the datatype datetime2(3)
like a pro:
Because losing milliseconds in the datasphere is a coder's version of sleepwalking.
Calculations: handle with care
While performing time calculations, bigint
is your safe bet to avoid overflows. You can thank us later!
Because, in SQL world, prevention is every bit as exciting as multiplication!
Practical use-cases
Milliseconds come in handy in real-world application scenarios:
- Performance tracking: Determining which block of code is taking longer than expected.
- Data synchronization: Ensuring systems are in sync down to the millisecond.
- Sequencing events: Determining the order of events in a time-sensitive system.
- Error tracking: Logging the exact time an error occurred can be crucial when debugging.
Friend or foe? SQL Server versions
Use FORMAT
to your heart's content on SQL Server 2012 and above. But for earlier versions, stick with CONVERT
. You've got this!
Was this article helpful?