2014-10-01 167 views
-1

我想從一個表中選擇值到另一個表中並使每行都插入一個唯一的日期時間條目。我遇到的問題是GETDATE()或SYSUTCDATETIME()函數似乎不夠快,我得到重複的日期時間條目。如何將記錄從一個表插入另一個表並插入具有唯一日期時間值

例如 創建表#T1 (tnum INT)

insert into #T1 select 1 
insert into #T1 select 2 
insert into #T1 select 3 

create table #T2 
(
Id int identity(1,1), 
tnum int, 
entrydate datetime 
) 

insert into #T2 SELECT #T1.tnum, getDate() FROM #T1 

select * from #T2 

這導致以下

1 1 2014-10-01 11:14:15.673

2 2 2014-10-01 11:14:15.673

3 3 2014-10-01 11:14:15.673

我的表設計使用datetime列作爲唯一索引的一部分,我需要這些是唯一的。我希望的結果會是這樣的

1 1 2014-10-01 11:14:15.673

2 2 2014-10-01 11:14:15.674

3 3 2014-10-01 11:14:15.675

我使用的是Microsoft SQL Server 2008的

+0

「GETDATE()或SYSUTCDATETIME( )功能似乎不夠快,我得到重複的日期時間條目。「你是不是認爲看起來*速度太快,因爲你得到重複的日期?這聽起來像你試圖使用日期時間作爲主鍵或類似的,是否有這樣的原因? – Kritner 2014-10-01 15:31:12

+0

爲什麼不使用TimeStamp字段? – ericpap 2014-10-01 15:32:26

+0

然後修復你的餐桌設計。 – Paparazzi 2014-10-01 16:04:14

回答

0

的選擇是好的,但你應該使用datetime2列的格式,因爲它可以讓你存放更精確的時間值。

datetime2有100個nanosecs的精度,而不是datetime,它舍入到.003.005.007

UPDATE

或者你換你的INSERT語句在while循環,每一步都在那裏包括幾個毫秒的睡眠。

我創造了這個小提琴,在這裏你可以看到這是如何工作(在MSSQL):http://sqlfiddle.com/#!3/62f0d/2

基本上,塊,就像上面描述:

/* @i represents a number of transactions, it can be equal to a count(*) for example */ 

WHILE (@i <= 3) 
    BEGIN 
    INSERT INTO #results VALUES (@i ,getDate(), getDate()) 
    WAITFOR DELAY '00:00:00.002' 
    SET @i = @i + 1 
END 
相關問題