Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-sql, ticks, timestamp

Is it possible to get something C# like DateTime.Ticks in t-sql ?

thanks for help

like image 724
gruber Avatar asked Feb 22 '11 15:02

gruber


People also ask

What is Unix timestamp in SQL Server?

A Unix timestamp (also known as Unix Epoch time, Unix time, or POSIX time) is simply the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC). Therefore, in SQL Server we can use a couple of T-SQL functions to return this. SQL Server Unix Timestamp

What is current_timestamp in SQL Server?

This function returns the current database system timestamp as a datetimevalue, without the database time zone offset. CURRENT_TIMESTAMPderives this value from the operating system of the computer on which the instance of SQL Server runs. Note

Can't convert between datetime2 and ticks in SQL Server?

But sometimes things are out of your control. If you do want to convert between datetime2 and ticks inside SQL Server instead of letting the application handle it, then you need to do some date math. It can get a bit tricky avoiding arithmetic overflows and keeping things accurate:

What is a tick in datetime?

A .Net tick is a duration of time lasting 0.1 microseconds. When you look at the Tick property of DateTime, you’ll see that it represents the number of ticks since January 1st 0001.


1 Answers

It's unlikely you'll be able to get the same kind of accuracy out of SQL as DateTime.Ticks since SQL doesn't express time in that much precision. SQL Server only stores time to approximately 1/300th of a second, whereas a single tick represents one hundred nanoseconds or one ten-millionth of a second.

SELECT DATEDIFF(s, '19700101', GETDATE()) 

The above query will get you a Unix-style timestamp if that works, but to make any real suggestions I'd need to know what you're using the data for. If you need higher resolution than 3 ms though, you need to look outside of SQL.

               DATETIME: 0.01      (3 ms)
QueryPerformanceCounter: 0.0000001 (100 ns)
              DATETIME2: 0.0000001 (7 decimal places, 100 ns)
like image 177
David Perry Avatar answered Sep 25 '22 03:09

David Perry