Here's a solution that populates the table in one step:
insert into T1 (StartDate, EndDate) select X.StartDate, dateadd(day, abs(checksum(newid())) % 10, X.StartDate) EndDate from ( select top 20 dateadd(day, -abs(checksum(newid())) % 100, convert(date, getDate())) StartDate from sys.columns c1, sys.columns c2 ) X
The above query uses some tricks, which I often often use in special SQL queries:
new_Id() generates different random values ββfor each row, unlike RAND() , which will be evaluated once per request. The expression abs(checksum(newid())) % N generates random integer values ββin the range 0 - N-1 .- the
TOP X ... FROM sys.columns c1, sys.columns c2 allows you to generate X rows whose values ββcan be composed of scalar values, such as those shown in our example.
Obviously, you can change the hardcoded values ββin the above query to:
- generate more lines
- increase the range of random start dates
- increase the maximum duration of each line.
source share