简体   繁体   中英

SQL Select record order by the date the record was created

I have A Legacy system that runs on a SQL Server 2005.

Current table only have date column YYYYMMDD, it lacks for both a running sequence number and time.

Is it possible to select the a table and order by chronological? or in other words, sort the return result with records are sorted base on the date and time the record was created.

If you do not have any valid time information or other information - like a vector autonumbering (IDENTITY), which was not modified - then the general answer is NO

BUT

The devil is in the details - it depends on database engine you use.

Just so that it might help someone else out. (I realize that that OP mentions MSSQL 2005)

In SQL 2008 and higher, you can use the %%physloc%% virtual column for this. This is undocumented and unsupported. However, it has proven to be helpful in many cases.

The hexadecimal values in %%physloc%% not only indicate the file number and page number; they also specify the slot number within the page. However, the encoding is not really human readable.

The following functions can be used to make sense of the values in this virtual column.

1. The sys.fn_PhysLocFormatter function

This function turns the hex value returned by %%physloc%% into a nice human-readable format. You can use it like this:

SELECT *,sys.fn_PhysLocFormatter(%%physloc%%) AS PLF
  FROM dbo.tst AS T
ORDER BY PLF;

The output of this function has the format (FileNumber:PageNumber:SlotNumer) . Below is the output of above query:

sys.fn_PhysLocFormatter

2. The sys.fn_PhysLocCracker function

This is a table valued function, you have to use the CROSS APPLY statement to call it within a query:

SELECT * FROM dbo.tst AS T
CROSS APPLY sys.fn_PhysLocCracker(%%physloc%%) AS FPLC
ORDER BY FPLC.file_id, FPLC.page_id, FPLC.slot_id;

It returns three columns: file_id , page_id and slot_id . Used with the same table you have seen in the previous example, the output looks like this:

sys.fn_PhysLocCracker


References:

Where are my Rows? – Using the %%physloc%% Virtual Column

SQL Server - Find Physical Location of Records

SQL Server 2008: New (undocumented) physical row locator function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM