What is the practical use of timestamp column in sql server with example?

后端 未结 3 2029
时光说笑
时光说笑 2021-02-01 02:15

I came across the timestamp datatype in sql server.What is the practical use of timestamp column in sql server with example?

3条回答
  •  后悔当初
    2021-02-01 02:55

    Let's take an example of a sale order table to illustrate what timestamp does.

    create table saleorder (ordernumber int, amount int, timestamp);
    insert into saleorder (ordernumber, amount) values (1, 100), (2, 100), (3, 200);
    select * from saleorder
    

    Notice the data in timestamp column. Documentation of timestamp (SQL Server 2005) says: This (i.e. timestamp) tracks a relative time within a database, not an actual time that can be associated with a clock...Every time that a row with a timestamp column is modified or inserted, the incremented database timestamp value is inserted in the timestamp column.

    Let's see how the data looks like:

    ordernumber amount  timestamp
    1           100     0x00000000000007D1
    2           100     0x00000000000007D2
    3           200     0x00000000000007D3
    

    Alright. Order 1 was added first and order 3 was entered last. What happens if we were to update amount of order 1?

    update saleorder set amount = 200 where ordernumber = 1
    select * from saleorder
    

    Ah, notice that order 1's timestamp is now 0x7D4 (Decimal 2004). In relation to other rows, we know that order 1 was updated most recently. But, more importantly, the value of timestamp comes when concurrent writes are happening.

    ordernumber amount  timestamp
    1           200     0x00000000000007D4
    2           100     0x00000000000007D2
    3           200     0x00000000000007D3
    

    Let's say John and Mary are both in sales attending to order 3 using a web application developed in, say, .NET. John pulls up the order and makes changes. John hasn't saved the data yet. Mary pulls the same order and changes it. John saves first. Mary attempts to save the data. .NET application can first look to see if the timestamp Mary pulled is still the same that the database has for order 3.

    If the timestamp Mary pulled with order 3 is now different (because John saved data and timestamp automatically got changed), the .NET application can alert Mary and ask her to refresh the record on her screen to see the latest change (or probably highlight the change on-screen).

    Think of timestamp as a row version. Interestingly, SQL Server's latest editions use rowversion datatype, which is synonymous with timestamp datatype. Documentation of rowversion (SQL Server 2012) has some interesting examples.

提交回复
热议问题