【问题标题】:SQL Server time stamp column insertion or updation possible explicitly?SQL Server 时间戳列插入或更新可能显式?
【发布时间】:2014-08-08 12:19:19
【问题描述】:

有没有办法为 SQL Server 表中的时间戳列提供显式值?我知道它不是 datetime 列,但我想知道是否有任何方法可以显式插入或更新它。

【问题讨论】:

    标签: sql-server timestamp


    【解决方案1】:

    据我所知,时间戳代表一个行版本号(这就是为什么当您更新行中的值时它们会发生变化,因为您正在创建该行的另一个版本)。事务日志中可能有一个日期,该日期说明了该行版本的出现时间。我不认为可以直接将时间戳转换为日期时间。

    嗯..我唯一的另一个想法是添加另一列,然后在其中选择时间戳值!最奇怪的是,这样做会将最后一个字符带回一个!看看你的想法。

    drop table abc
    go
    create table abc
    (
    col1 int, timestamp
    )
    go
    insert into abc(col1) values (1)
    go
    alter table abc add timestamp# varbinary(18)
    go
    update abc set timestamp# = convert(varbinary,timestamp)
    

    一般来说,在创建表时,我会包含一个默认为日期时间的列,这样您在创建每一行时都有一个日期时间。

    像这样:

    drop table def
    go
    create table def
    (
    col1 int,
    idt datetime default getdate()
    )
    

    如果您在 col1 中插入一个值,并且在 insert 语句的列列表中不包含 idt,则 idt 列将默认为您插入该值的日期时间。

    像这样:

    insert into def (col1) values (1)
    

    【讨论】:

      【解决方案2】:

      因为时间戳似乎是您插入或更新列时数据库创建的时间戳的表示,实际上您必须更改数据库创建的原始时间戳才能显式定义它们。

      从您的第二条评论中,我很欣赏您可能会收到带有时间戳的数据,而您只希望这些数据以与使用“set identity_insert on”插入数据相同的方式显示在您的表上。

      答案是将现有表选择到另一个表中,然后添加传入数据。如果你运行下面的代码,我想你会明白我的意思。

      create table abc
      (
      col1 int, timestamp
      )
      go
      insert into abc(col1) values (1)
      go
      select col1,convert(varbinary,timestamp) timestamp# into def from abc
      go
      select * from abc
      select * from def
      

      【讨论】:

      • 感谢我们甚至可以将其转换为日期时间并执行相同操作的想法。最后我想在一个表格中确认我们不能这样做。
      【解决方案3】:

      您不能显式地插入/更新时间戳列。它们是在您对表执行插入/更新时自动生成的。

      【讨论】:

      • 我知道我只是想知道是否有任何类似标识列的标志设置类型可以设置为明确给出标识列。
      猜你喜欢
      • 1970-01-01
      • 2012-05-02
      • 2013-06-11
      • 2011-06-03
      • 2017-08-29
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多