You can use the @@DBTS
function to get the current rowversion of a given database in SQL Server. More specifically, it returns the last-used rowversion value of the current database.
Example 1 – Basic Usage
To use the @@DBTS
function, simply select it within a SELECT
statement.
Like this:
SELECT @@DBTS;
Result:
+--------------------+ | (No column name) | |--------------------| | 0x0000000000000FA0 | +--------------------+
Example 2 – Different Databases
As mentioned, the rowversion value is specific to each database. Therefore, you need to make sure you’re in the right database.
Here’s an example to demonstrate:
USE Music; SELECT @@DBTS AS "Music rowversion"; Use WideWorldImportersDW; SELECT @@DBTS AS "WideWorldImportersDW rowversion";
Result:
Changed database context to 'Music'. +--------------------+ | Music rowversion | |--------------------| | 0x00000000000007D0 | +--------------------+ (1 row affected) Changed database context to 'WideWorldImportersDW'. +-----------------------------------+ | WideWorldImportersDW rowversion | |-----------------------------------| | 0x0000000000015F90 | +-----------------------------------+ (1 row affected)
Where is this Value Used?
The rowversion value is used by columns that have either a rowversion or timestamp data type. Such columns are automatically updated with a unique number, based on the incremented value of rowversion, whenever an insert or update occurs.
Using the above example, if I insert or update a row in the Music
database, and that row has a rowversion column, that column’s value will probably be set to 0x00000000000007D1
(i.e. 0x00000000000007D0
incremented by 1). At this stage, if I was to use @@DBTS
against that database, it would return 0x00000000000007D1
(because that’s the last-used rowcount value).
If I then update that row, its rowversion column will become 0x00000000000007D2
. This is true, even if the update operation didn’t actually change any data. This time, if I run @@DBTS
it would return 0x00000000000007D2
.
For an example that demonstrates this, see What is “rowversion” in SQL Server.
The timestamp data type is actually a synonym for rowversion, so the value returned by @@DBTS
reflects the current rowversion value whether it was incremented by a rowversion column or a timestamp column.
Also note that timestamp is one of four deprecated data types that are in maintenance mode and may be removed in a future version of SQL Server. Therefore you should use rowversion instead of timestamp in new development work. You should also plan to modify applications that currently use timestamp.