SQL返回两个时间范围内的一个随机时间

更新时间:2023-07-26 20:20:03 阅读: 评论:0

/******************************
*    函数名:RandDateTime
*    作用: 返回两个时间范围内的一个随机时间
中华神皂*    Author:    兰习刚
*    Date:      2009-11-30
*******************************/
go
--创建函数
create Function RandDateTime
(
    @RandNum Decimal(38,18),--0-1之际随机数值建议Rand()
    @StartTime DateTime,    --第一个时间
    @EndTime DateTime       --第二个时间
)
Returns DateTime
As
Begin
    Declare @HourDiff Decimal(38,18)    --两个时间之间的小时差值
    Declare @MsPartDiff传统节日的由来 Decimal(38,18)  --毫秒部分的差值 
    Declare @SmallDate DateTime
    Declare @ReturnDateTime DateTime   
   
    /*取各部分差值*/
    Set @HourDiff = DateDiff(hh,@StartTime,@EndTime)
    Set @MsPartDiff = Abs(DateDiff(ms,DateAdd(hh,@HourDiff,@StartTime冬天英文怎么读),@EndTime))
    Select @SmallDate=(Ca When @HourDiff>地中海实蝇0 Then @StartTime El @EndTime End)    --取较小的时间 
    Set @HourDiff = Abs(@HourDiff)
竞聘演讲ppt
    ActionLable:
    Declare @HourDecimal Decimal(38,18)    --小时的小数部分 
    Declare @HourString varchar(200)
    Set @HourDiff = @HourDiff * @RandNum   
    Set @HourString = CONVERT(VARCHAR(200),@HourDiff)
    Set @HourString = SubString(@HourString,CharIndex('.',@HourString)+1,Len(@HourString))
    Set @HourString = '0.' + @HourString地质考研
    Set @HourDecimal = Convert(Decimal(38,18),@HourString)    --获得小时的小数部分
    Set @MsPartDiff = (@MsPartDiff + @HourDecimal * 3600*1000) * @RandNum   
    /*毫秒差值
    由于之前@MsPartDiff是两个时间小时之后的毫秒差值 
    @HourDecimal * 3600*1000 有小时的小数部分的毫秒差值不会大于小时
    毫秒不会溢出
    */
    Set @ReturnDateTime = DateAdd(hh,@HourDiff,@SmallDate)
    Set @ReturnDateTime = DateAdd(ms,@MsPartDiff,@ReturnDateTime)       
听筒模式怎么关闭    Return @ReturnDateTime
End
 
--测试示例
lect dbo.RandDateTime(Rand(),'2011-03-21 00:00:00.000','2011-03-21 23:59:00.000')
go 10
 
--运行结果
/*
-----------------------
2011-03-21 16:44:58.990
 
(1 row(s) affected)
 
 
-----------------------
2011-03-21 00:00:33.313
 
(1 row(s) affected)
善行
 
 
-----------------------
2011-03-21 15:04:58.777
 
(1 row(s) affected)
 
 
-----------------------
2011-03-21 06:32:21.347
 
(1 row(s) affected)
 
 
-----------------------
2011-03-21 15:11:51.047
 
(1 row(s) affected)
 
 
-----------------------
2011-03-21 14:39:23.597
 
(1 row(s) affected)
 
 
-----------------------
2011-03-21 07:24:17.247
 
(1 row(s) affected)
 
 
-----------------------
2011-03-21 06:15:49.653
 
(1 row(s) affected)
 
 
-----------------------
2011-03-21 02:06:14.757
 
(1 row(s) affected)
 
 
-----------------------
2011-03-21 10:49:18.370
 
(1 row(s) affected)
*/

本文发布于:2023-07-26 20:20:03,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/1097811.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:小时   部分   差值   小数
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图