How do you use the ROWVERSION data type to automatically generate unique binary numbers?
Posted by IreneSm
Last Updated: July 20, 2024
In SQL Server, the ROWVERSION data type (which is also known as TIMESTAMP, although that name is deprecated) is a data type that automatically generates unique binary numbers within a database. It is often used to maintain versioning and concurrency control.
How ROWVERSION Works
- Unique Only Within a Database: Each instance of a ROWVERSION column in a table is unique within the entire database. It doesn't guarantee uniqueness across databases. - Automatic Generation: When a new row is inserted into a table with a ROWVERSION column, SQL Server automatically generates a unique binary number for that column. This number is generated based on a sequential counter maintained by SQL Server.
Steps to Use ROWVERSION
1. Create a Table with ROWVERSION Column: When creating a new table, you can specify a column of type ROWVERSION. Here’s an example:
CREATE TABLE MyTable (
       ID INT PRIMARY KEY,
       Data NVARCHAR(100),
       RowVer ROWVERSION
   );
In this example, RowVer is the ROWVERSION column. 2. Insert Data: When you insert data into the table, you do not need to specify a value for the ROWVERSION column; SQL Server will automatically generate it.
INSERT INTO MyTable (ID, Data) VALUES (1, 'Sample Data');
   INSERT INTO MyTable (ID, Data) VALUES (2, 'Another Sample');
3. Query the Table: You can retrieve the generated ROWVERSION values along with your data by querying the table.
SELECT ID, Data, RowVer FROM MyTable;
The RowVer column will have unique binary values for each row. 4. Using ROWVERSION for Concurrency Control: You can use the ROWVERSION column to implement optimistic concurrency control. When updating a row, you can check the ROWVERSION value to ensure that no other transaction has modified the row since it was last read. For example:
DECLARE @currentRowVer ROWVERSION;
   SELECT @currentRowVer = RowVer FROM MyTable WHERE ID = 1;

   -- Suppose we have some logic that determines whether to update
   IF EXISTS (SELECT * FROM MyTable WHERE ID = 1 AND RowVer = @currentRowVer)
   BEGIN
       UPDATE MyTable
       SET Data = 'Updated Data'
       WHERE ID = 1;
   END
   ELSE
   BEGIN
       PRINT 'The row has been modified by another transaction.';
   END
Important Notes
- ROWVERSION is not intended for storing date/time values, despite the name TIMESTAMP. It is purely a versioning mechanism. - If you want to retrieve the value of ROWVERSION as a hexadecimal string, you can use the CONVERT function. By following these steps, you can effectively use the ROWVERSION data type to automatically generate unique binary numbers in your SQL Server database.