循环插入一定时间范围内的随机日期值

ZDNet软件频道 时间:2009-12-03 作者: | 赛迪网 我要评论()
本文关键词:Server 服务器 SQL
-- here for the demo, but this could be done anyway you like. DECLARE @date_from DATETIME;-- Therefore, we have to take the modulus of the -- date range difference.-- To get the number of days in the date range, we

  -- First, let's declare the date range. I am declaring this

  -- here for the demo, but this could be done anyway you like.

  DECLARE @date_from DATETIME;

  DECLARE @date_to DATETIME;

  -- Set the start and date dates. In this case, we are using

  -- the month of october, 2006.

  SET @date_from = '2006-10-01';

  SET @date_to = '2006-10-30';

  -- insert random dates.

  insert into randomdate SELECT

  (

  -- Remember, we want to add a random number to the

  -- start date. In SQL we can add days (as integers)

  -- to a date to increase the actually date/time

  -- object value.

  @date_from +

  (

  -- This will force our random number to be GTE 0.

  ABS(

  -- This will give us a HUGE random number that

  -- might be negative or positive.

  CAST(

  CAST( NewID() AS BINARY(8) )

  AS INT

  )

  )

  -- Our random number might be HUGE. We can't have

  -- exceed the date range that we are given.

  -- Therefore, we have to take the modulus of the

  -- date range difference. This will give us between

  -- zero and one less than the date range.

  %

  -- To get the number of days in the date range, we

  -- can simply substrate the start date from the

  -- end date. At this point though, we have to cast

  -- to INT as SQL will not make any automatic

  -- conversions for us.

  CAST(

  (@date_to - @date_from)

  AS INT

  )

  )

  )

Server

服务器

SQL


百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134