Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get date/time information from a TIMESTAMP column?

It seems that the TIMESTAMP information is encrypted in some way, where the date/time data is somehow encoded in binary. I just want to discover all the rows that were modified today.

like image 497
Aaron Bertrand Avatar asked Aug 22 '11 23:08

Aaron Bertrand


People also ask

How do I extract a date from a timestamp column?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column. (In our example, we use a column of the timestamp data type.)

How do I get the date part of a timestamp?

You can use date(t_stamp) to get only the date part from a timestamp. Extracts the date part of the date or datetime expression expr.


1 Answers

TIMESTAMP is an unfortunate name the SQL Server team gave the data type. It is for concurrency, and has nothing to do with date or time - they've recommended using its alias, ROWVERSION to prevent confusion. From this Books Online article, "In DDL statements, use rowversion instead of timestamp wherever possible."

Unfortunately you won't be able to derive any date/time details from the ROWVERSION column you already have, but if this information is important, you should add CreatedDate / ModifiedDate columns, for example:

ALTER TABLE dbo.foo ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE dbo.foo ADD ModifiedDate DATETIME NULL;

Then create a TRIGGER that fires on UPDATE to keep the ModifiedDate value current. You may need to decide whether you want the ModifiedDate to be NULL or equal to CreatedDate on initialization.

like image 90
Aaron Bertrand Avatar answered Oct 05 '22 19:10

Aaron Bertrand