SQL Server:无法将显式值插入时间戳列

新手上路,请多包涵

使用此语句时

create table demo (
    ts timestamp
)

insert into demo select current_timestamp

我收到以下错误:

无法将显式值插入时间戳列。将 INSERT 与列列表一起使用以排除时间戳列,或将 DEFAULT 插入时间戳列

如何将当前时间插入 timestamp 列?

原文由 juergen d 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.9k
2 个回答

根据 MSDNtimestamp

是一种在数据库中公开自动生成的唯一二进制数的数据类型。时间戳通常用作对表行进行版本标记的机制。存储大小为 8 个字节。时间戳数据类型只是一个递增的数字,不保留日期或时间。要记录日期或时间,请使用 datetime 数据类型。

您可能正在寻找 datetime 数据类型。

原文由 Andomar 发布,翻译遵循 CC BY-SA 3.0 许可协议

这些答案中有一些很好的信息。假设您正在处理无法更改的数据库,并且您正在将数据从表的一个版本复制到另一个版本,或者从一个数据库中的同一个表复制到另一个。还假设有很多列,并且您需要来自所有列的数据,或者您不需要的列没有默认值。您需要编写一个包含所有列名的查询。

这是一个查询,它返回表的所有非时间戳列名称,您可以将其剪切并粘贴到插入查询中。仅供参考:189 是时间戳的类型 ID。

 declare @TableName nvarchar(50) = 'Product';

select stuff(
    (select
        ', ' + columns.name
    from
        (select id from sysobjects where xtype = 'U' and name = @TableName) tables
        inner join syscolumns columns on tables.id = columns.id
    where columns.xtype <> 189
    for xml path('')), 1, 2, '')

只需将顶部的表格名称从“产品”更改为您的表格名称。查询将返回列名列表:

 ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate

如果要将数据从一个数据库 (DB1) 复制到另一个数据库 (DB2),则可以使用此查询。

 insert DB2.dbo.Product (ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate)
select ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate
from DB1.dbo.Product

原文由 Kent Weigel 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进