2013-02-14 74 views
3

能否請你幫:隨機化日期SQL

我有一個需要5000行增加了它與隨機日期從2010年度

例如一個抵達的日期列:01/01/201025/8/201003/05/201031/12/2010

我認爲這將是一個INSERT聲明,但我不確定。

感謝

韋恩

USE Occupancy 
CREATE TABLE Book 
(BookNumber varchar(30), 
ArrivalDate int) 

DECLARE @BookNumber varchar(30) 
DECLARE @ArrivalDate int 

SET @BookNumber = 1 
SET @ArrivalDate = 0 

WHILE @BookNumber <= 5000 
WHILE @ArrivalDate <= 5000 

BEGIN 
INSERT INTO Book (BookNumber,ArrivalDate) 
SELECT 'B' + Right ('00000000' + CAST(@BookNumber AS varchar(30)),8), 
DATEADD(day, CAST(RAND() * 365 as int), '2010-1-1') 

SET @BookNumber = @BookNumber + 1 
SET @ArrivalDate = @ArrivalDate + 1 
END 
+0

[相關](HTTP:// stackoverflow.com/questions/5519486/select-a-random-date-within-specific-range),[也相關](http://stackoverflow.com/questions/794637/how-to-update -rows上帶有一個隨機至今)。 – Dukeling 2013-02-14 15:29:23

回答

5
DECLARE @counter int 
SET @counter = 0 
WHILE @counter < 5000 
BEGIN 
    INSERT INTO myTable (arrivalDate) 
    SELECT DATEADD(day, CAST(RAND() * 365 as int), '2010-1-1') 
    SET @counter = @counter + 1 
END 

如果你有一個數字表或generator,則可避免循環:

INSERT INTO myTable (arrivalDate) 
SELECT DATEADD(day, ABS(CHECKSUM(NEWID()) % 365), '2010-1-1') 
FROM (GenerateRowNumbers(5000, 1)) t 
+0

優秀,喜歡它。一個更新雖然:* SET @counter = 0 *我認爲是你的意思。 – Kprof 2013-02-14 15:35:04

+0

你的第二個例子會爲每一行生成相同的值 - 「RAND()」只被調用一次。 – 2013-02-14 15:35:34

+0

@Kprof,錯字 - 固定 – PinnyM 2013-02-14 15:36:00