惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - leohuang

C#日期函数使用大全 replace(/\s/g,"")中的/g是什么意思? 及replace函数的用法 - leohuang - 博客园 为什么就没有中文版 数据库设计和优化 的书呢 - leohuang 巧用httpModules实现网站域名更换 asp.net 下发布水晶报表调试经验 C#操作Access的一些小结 - leohuang Photoshop制作Favicon.ico图标(转载) 取消ie6自动打开excel - leohuang - 博客园 oracle多表查询分页 库存出入库算法 Page_Load为什么会执行两次 - leohuang - 博客园 asp网站(asp+access)怎么防注入呢 Windows Service开发日志(转载csdn) IFrame 下返回登录页 访问母板页的updatepanel 及 设置 密码框字符 - leohuang 垃圾的江苏电信 amd 2500 boot设置 总算下到 Expert C# 2008 Business Objects 了 读《Expert C# 2005 Business Object》 - leohuang
Timestamp (rowversion) Data Type
leohuang · 2010-03-02 · via 博客园 - leohuang

http://www.sqlusa.com/articles2005/rowversion/

Timestamp (rowversion) Data Type

By Kalman Toth, M.Phil., M.Phil., MCDBA, MCITP

November 17 , 2009

A table can have only one timestamp column. The value in the timestamp column is updated every time a row containing a timestamp column is inserted or updated. Of course this means we should not use it as a primary key, because we can get many orphans quickly if updates are performed on other columns. As a row is modified in a table, the timestamp is updated with the current database timestamp value obtained from the @@DBTS function.

Timestamp is the wrong name, quite confusing in fact. It has nothing to do with time. Microsoft will rename it rowversion in the future. Rowversion is the synonym for timestamp in SQL Server 2005 and SQL Server 2008.

It is an 8 bytes unique binary key within the database.

Here is how it looks like: 0x0000000000000743. After an update to the row: 0x0000000000000745.

The rowversion(timestamp) starts changing as soon as the transaction begins. If the transaction is rolled back, it returns to the original value.

So how can we use it?

The main purpose is row versioning in multi user environment, in other words concurrency checking.
Assume you are a developer and developing a program in Visual Basic to update the name and address table of customers. There will be 100 staff member who can perform this application function. How can you be sure that while staff A typing in the change, staff X is not changing the same row?

Here is what you do:

1. Read the name and address table including the timestamp. You display the info to the user for update and save the timestamp.
2. Certain amount of time later, like 2 minutes, the user presses the submit button after changes were typed in.
3. You open a transaction with Begin Transaction
4. You read the timestamp of the name and address row
5. You compare the current timestamp to the saved timestamp.
6. If the timestamps are same, you update the row and commit the transaction
7. If timestamps are different, you roll back the transaction and notify the user about the fact that the data was changed by someone else. You can let the user decide what to do or follow the appropriate company business rule for data entry conflict resolution.

This is pretty common practice in multi user environment. The alternate would be to examine a datetime column, or the entire row which is more processing intensive.

The following example shows timestamp (rowversion in SQL Server 2008) in action:

-- SQL Server 2008 T-SQL Code

USE tempdb;

-- SQL create table for Concurrency Checking demo

CREATE TABLE Celebrity (

  CelebrityID INT    IDENTITY    PRIMARY KEY,

  FirstName   VARCHAR(25),

  LastName    VARCHAR(30),

  VERSIONSTAMP  ROWVERSION)

GO

-- SQL insert - populate table

INSERT Celebrity (FirstName, LastName)

VALUES

('Jessica', 'Simpson'),

('Nick', 'Carter'),

('Stevie', 'Brock'),

('Christina', 'Aguilera'),

('Frank','Sinatra'),

('Doris','Day'),

('Elvis', 'Presley')

GO

SELECT * FROM Celebrity

GO

/* Results

CelebrityID FirstName   LastName    VERSIONSTAMP

1           Jessica     Simpson     0x0000000000000876

2           Nick        Carter      0x0000000000000877

3           Stevie      Brock       0x0000000000000878

4           Christina   Aguilera    0x0000000000000879

5           Frank       Sinatra     0x000000000000087A

6           Doris       Day         0x000000000000087B

7           Elvis       Presley     0x000000000000087C

*/

-- SQL update demo: SOMEONE UPDATED RECORD since it was read

CREATE TABLE #Semaphore (ID int identity(1,1) primary key,

                          StartVersion bigint,

                          PK int)

DECLARE @MyKey int

INSERT INTO #Semaphore (StartVersion, PK)

SELECT  VERSIONSTAMP, 1

FROM Celebrity WHERE CelebrityID=1

SELECT @MyKey = SCOPE_IDENTITY()

-- SIMULATION: somebody else updating the same record

UPDATE Celebrity

SET    FirstName = 'Celine',

       LastName = 'Dion'

WHERE  CelebrityID = 1

-- We are attempting to update.

BEGIN TRANSACTION

IF (SELECT StartVersion

    FROM   #Semaphore

    WHERE  ID = @MyKey) = (SELECT VERSIONSTAMP

                           FROM   Celebrity

                           WHERE  CelebrityID = 1)

  BEGIN

    UPDATE Celebrity

    SET    FirstName = 'Lindsay',

           LastName = 'Lohan'

    WHERE  CelebrityID = 1

    COMMIT TRANSACTION

  END

ELSE

  BEGIN

    ROLLBACK TRANSACTION

    PRINT 'ROLLBACK - UPDATE CONFLICT'

    RAISERROR ('Celebrity update conflict.',10,0)

  END

DELETE #Semaphore WHERE ID = @MyKey

SELECT * FROM   Celebrity

GO

/* CelebrityID    FirstName   LastName    VERSIONSTAMP

1           Celine      Dion        0x000000000000087D

2           Nick        Carter      0x0000000000000877

3           Stevie      Brock       0x0000000000000878

4           Christina   Aguilera    0x0000000000000879

5           Frank       Sinatra     0x000000000000087A

6           Doris       Day         0x000000000000087B

7           Elvis       Presley     0x000000000000087C

*/

-- SQL UPDATE with NO CONFLICT

DECLARE @MyKey int

INSERT INTO #Semaphore (StartVersion, PK)

SELECT  VERSIONSTAMP, 1

FROM Celebrity WHERE CelebrityID=1

SELECT @MyKey = SCOPE_IDENTITY()

-- We are trying to update.

BEGIN TRANSACTION

IF (SELECT StartVersion

    FROM   #Semaphore

    WHERE  ID = @MyKey) = (SELECT VERSIONSTAMP

                           FROM   Celebrity

                           WHERE  CelebrityID = 1)

  BEGIN

    UPDATE Celebrity

    SET    FirstName = 'Lindsay',

           LastName = 'Lohan'

    WHERE  CelebrityID = 1

    COMMIT TRANSACTION

  END

ELSE

  BEGIN

    ROLLBACK TRANSACTION

    PRINT 'ROLLBACK - UPDATE CONFLICT'

    RAISERROR ('Celebrity update conflict.',10,0)

  END

DELETE #Semaphore WHERE ID = @MyKey

SELECT * FROM   Celebrity

GO

/*

CelebrityID FirstName   LastName    VERSIONSTAMP

1           Lindsay     Lohan       0x000000000000087E

2           Nick        Carter      0x0000000000000877

3           Stevie      Brock       0x0000000000000878

4           Christina   Aguilera    0x0000000000000879

5           Frank       Sinatra     0x000000000000087A

6           Doris       Day         0x000000000000087B

7           Elvis       Presley     0x000000000000087C

*/

-- Cleanup

DROP TABLE #Semaphore

DROP TABLE Celebrity

这篇写的比较好,通过rowversion控制并发操作。