SQL Server: Cannot insert an explicit value into a timestamp column

后端 未结 7 2036
无人及你
无人及你 2020-11-30 09:25

When using this statement

create table demo (
    ts timestamp
)

insert into demo select current_timestamp

I get the following error:

7条回答
  •  失恋的感觉
    2020-11-30 10:07

    How to insert current time into a timestamp with SQL Server:

    Answer: You can't, and here's why.

    In newer versions of SQL Server, timestamp is renamed to RowVersion. Rightly so, because timestamp is very misleading.

    SQL Server timestamp IS NOT set by the user and does not represent a date or time. timestamp is just a binary representation of a consecutive number, it's only good for making sure a row hasn't changed since it's been read.

    If you want to store a date or a time, do not use timestamp, you must use one of the other datatypes, like for example datetime, smalldatetime, date, time or DATETIME2

    For example:

    create table wtf (
        id INT,
        leet timestamp
    )
    
    insert into wtf (id) values (15)
    
    select * from wtf
    
    15    0x00000000000007D3 
    

    So timestamp is some kind of binary number. What if we try casting it to datetime?

    select CAST(leet AS datetime) from wtf
    
    1900-01-01 00:00:06.677
    

    The current year for me is not 1900. So I'm not sure what SQL Server is thinking.

提交回复
热议问题