在Sql中几种取随机数的方法:

时间:2022-08-01 04:40:31

一、

DECLARE@BDatedatetime, @EDatedatetime
SET@BDate='20090101'          --下限
SET@EDate='20101231 23:59:59'--上限
SELECT n, random_datetime =DATEADD(second,ABS(CHECKSUM(NEWID()))%DATEDIFF(second,@BDate,@Edate),@BDate)
FROM dbo.Nums
WHERE n BETWEEN1AND100

二、

DECLARE@dt1DATETIME,@dt2DATETIME,@aBIGINT,@bBIGINT
SET@dt1='2010-01-01'--開始日期
SET@dt2='2010-06-30'--結束日期

SELECT@a=CAST(@dt1ASBIGINT),@b=CAST(@dt2-@dt1ASBIGINT)

DECLARE@tTABLE(ID INT,dt datetime)

DECLARE@iINT
SET@i=0

WHILE@i<100
BEGIN
    INSERT@t
    SELECT
        @i+1,CAST(ABS(CHECKSUM(newID()))%@b+@aASDATETIME)+RAND()
    SET@i=@i+1
end
SELECT*FROM@t

三、

SQL code
SELECT
TOP 100
ROW_NUMBER()OVER(ORDER BY a.ID) AS ID,
CAST(CHECKSUM(newID())%40357 AS DATETIME)+RAND() AS 隨機值
FROM syscolumns a,syscolumns b