【问题标题】:set hour, minute and seconds to exact numbers in sql在sql中将小时、分钟和秒设置为精确的数字
【发布时间】:2016-08-02 14:57:46
【问题描述】:

感谢http://mitchelsellers.com/blogs/2008/09/12/creating-random-sql-server-test-data.aspx,我正在使用虚拟信息填充我的数据库以进行测试,并且它正在工作,但是我的日期是随机的,并且得到随机的年/月,但始终是当前时间,从我的数据库中提取了一些示例:

2017-05-30 16:41:53.190
2017-07-21 16:41:53.193
2016-04-23 16:41:53.193

但是我使用这些日期的申请必须以

的形式出现
2017-05-30 16:00:00.000
2017-07-21 01:30:00.000
2016-04-23 04:45:00.000

换句话说,日期当前很好,但minute 应该是00,15,30,45secondsmiliseconds 应该总是00

有什么方法可以将上述格式的随机时间添加到我的 sql 中?

我目前的SQL逻辑如下:

DECLARE @RowCount INT
DECLARE @RowString VARCHAR(10)
DECLARE @Random INT
DECLARE @Upper INT
DECLARE @Lower INT
DECLARE @InsertDate DATETIME
DECLAre @LoopThisManyTimes INT

SET @Lower = -360 /* move 360 days backwards */
SET @Upper = 360 /*  move 360 days forward */
SET @RowCount = 0 /* start the counter at 0 */
SET @LoopThisManyTimes = 10 /* set the number of posts to add */

USE [Scheduler]
TRUNCATE TABLE [dbo].[Appointments] /* clear table for testing purposes */
WHILE @RowCount < @LoopThisManyTimes /*loop and add to table */
BEGIN
SET @RowString = CAST(@RowCount AS VARCHAR(10))
    SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
    SET @InsertDate = DATEADD(dd, @Random, GETDATE())

【问题讨论】:

    标签: sql datetime random


    【解决方案1】:

    只需几秒钟而不是几天即可完成计算。这是一种方法:

    WHILE @RowCount < @LoopThisManyTimes /*loop and add to table */
    BEGIN
        SET @RowString = CAST(@RowCount AS VARCHAR(10));
        SELECT @Random = ROUND(((@Upper - @Lower -1)*60*60*24 * RAND() + @Lower*60*60*24), 0);
        SET @InsertDate = DATEADD(second, @Random, GETDATE());
    END;
    

    编辑:

    如果您想要固定分钟数:

    WHILE @RowCount < @LoopThisManyTimes /*loop and add to table */
    BEGIN
        SET @RowString = CAST(@RowCount AS VARCHAR(10));
        SELECT @Random = ROUND(((@Upper - @Lower -1)*4*24 * RAND() + @Lower*4*24), 0);
        SET @InsertDate = DATEADD(minute, @Random*15, CAST(GETDATE() as DATE));
    END;
    

    我认为算术是对的。

    【讨论】:

    • 现在如此接近,很好的答案,现在我得到了随机的时间冲程,但我需要分钟才能始终为 00、15、30 或 45,秒 + 毫秒分别为 00 和 000。朝着正确的方向迈出了良好的第一步,谢谢。
    • @darrrrUC:将 60*60*24 更改为 60/15*60*24 并将 DATEADD 更改为 (second, CAST(@Random*15 AS INTEGER), GETDATE()) 以获得 15 秒的增量
    • 它们还没有四舍五入:)
    • @darrrrUC 是的,你需要先投射:CAST(@Random AS INTEGER) *15
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 2011-09-12
    • 1970-01-01
    • 2015-06-02
    相关资源
    最近更新 更多