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

     -- 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
     )
     )
     )
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值