【发布时间】:2015-12-02 22:17:13
【问题描述】:
或者:如何将时间戳数据从一个表复制到另一个表?
使用 SQL Server 2008 并拥有旧的设计文档,这需要一个表以某种方式对列进行排序(timestamp 列最后,我猜这来自使用 Excel 而不是 SQL 数据库的时间)我需要在表格中间添加一列,保持timestamp 数据完整...
您知道如何指示 SQL Server 执行此操作吗?
示例 T-SQL 代码:
-- In the beginning...
CREATE TABLE TestTableA
(
[TestTableAId] [int] IDENTITY(1,1) NOT NULL,
[TestTableAText] varchar(max) NOT NULL,
[TestTableATimeStamp] [timestamp] NOT NULL
)
INSERT INTO TestTableA (TestTableAText) VALUES ('TEST')
-- 很多年过去了……
-- 现在我们需要在这个表中添加一列,但保留所有数据,包括时间戳数据。 -- 附加要求:我们希望 SQL Server 将时间戳保留在列的最后。
CREATE TABLE TestTableB
(
[TestTableBId] [int] IDENTITY(1,1) NOT NULL,
[TestTableBText] varchar(max) NOT NULL,
[TestTableBInt] [int] NULL,
[TestTableBTimeStamp] [timestamp] NOT NULL
)
-- How do we copy the timestamp data from TestTableATimestamp to `TestTableBTimestamp`?
SET IDENTITY_INSERT [TestTableB] ON
-- Next line will produce errormessage:
-- Cannot insert an explicit value into a timestamp column. Use INSERT with a column list to exclude the timestamp column, or insert a DEFAULT into the timestamp column.
INSERT INTO [TestTableB] (TestTableBId, TestTableBText, TestTableBTimeStamp)
SELECT TestTableAId, TestTableAText, TestTableATimestamp
FROM TestTableA
SET IDENTITY_INSERT [TestTableB] OFF
GO
建议?
【问题讨论】:
-
与stackoverflow.com/questions/785305/… 有点相关,但尚未以有助于解决此问题的方式回答...
-
一个视图可能是一个可行的解决方案?这样,您可以按任何顺序放置字段,而不会更改实际表。
-
“时间戳”这个词在 SQL Server 中很笨拙,因为它与时间完全无关。如果您的列具有“时间戳”的数据类型,那么请仔细查看 Ben 的答案。我确实希望“时间戳”没有被用作列标题,那不会很好。请参阅sqlfiddle.com/#!3/84ea9/1 - 哦,对不起,我错过了将列指定为数据类型时间戳的 DDL - 抱歉
标签: sql-server database sql-server-2008 tsql timestamp