I have a SQL Server table with just 3 columns, one of which is of type varbinary. The data in this column is actually a Json document which among other properties contains information about when the data was last modified. Unfortunately the SQL table itself does not contain information about when its rows were modified.
Now when doing sorting and filtering of the data I of course don't want fetch all rows in order to find e.g. the latest 100 entries.
So my question is: does SQL Server somehow remember when a row was added/modified? I have tried adding a timestamp and this is applied to all existing rows but this is applied randomly I think, because the sorting doesn't work. I don't need a datetime or anything, I just want to be able sort the records based on when they were last modified.
Thanks
6条答案
按热度按时间wd2eg0qa1#
For those looking to insert a tamestamp column of type DateTime into an existing DB table, you can do this like so:
The existing records will automatically get the value equal to the date/time of the moment when column is added. New records will get up-to-date value upon insertion.
km0tfn4u2#
SQL Server will not track historically when a row was inserted or modified so you need to rely on the JSON data to figure that out yourself. You are going to need a new column to make this efficient to query. Once you have your new column you have some options:
The downside of this method is that you need to maintain this
And, create an index to make it efficient:
ncgqoxb03#
Use a new column CreatedDate and store datetime every time you make an Insert.
You could use GetDate() for inserting date in the column.
A UpdatedDate column can be used for updates.
w1jd8yoj4#
in order to find e.g. the latest 100 entries. Timestamp is indeed what you need.
It's ever-increasing value, it's updated automatically, so you are always able to find all last modified/inserted rows.
Here is an example:
As you see, you always get the last modified/inserted row.
For your purpose just use
x8goxv8g5#
Thanks. Apparently I didn't look hard enough before I posted this question. The question has been asked a couple of times before and the answer is: Nope! There is no easy solution to this.
SQL Server does not keep track of when a record was created or modified, which was somehow what I was looking for. So I will go for the next best solution, which is probably to create a datetime column, retrieve the modified date from the Json document and then update the record. Or rather, the 1,4 million records:-(
wlsrxk516#
ADDING TIMESTAMP TO AN EXISTING TABLE IN SQL SYNTAX: