或者:如何將時間戳數據從一個表複製到另一個表?如何在SQL Server(T-SQL)中更改表時保留時間戳記值?
使用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將TimeStamp保留在列的最後。
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
建議?
一定的相關性http://stackoverflow.com/questions/785305/keep-timestamp-when-copying-my-sql-server-database ?rq = 1但它沒有得到回答,有助於解決這個問題... – user3505708
一個視圖可能是一個可行的解決方案?通過這種方式,您可以將字段以任意順序放置,而不會改變實際的表格。 – Paolo
「timestamp」這個詞在SQL Server中有點笨拙,因爲它與時間無關。如果你的專欄的數據類型是「時間戳」,那麼請看本的答案。我希望「時間戳」沒有被用作列標題,這不會很好。請參閱http://sqlfiddle.com/#!3/84ea9/1 - 哦,對不起,我錯過了將列指定爲數據類型時間戳的DDL - 抱歉 –