SQLServer 随机生成指定范围的日期
一个分页的问题,DTCms3.0中,分页是根据时间分页的,如果当添加时间(add_time)都是同一个数值时,不管点击第几页,显示的数据都是同一个的内容,于是就有了需要把同一个时间改指定随机日期的功能。
原贴脚本转至http://bbs.csdn.net/topics/340165720 第7楼的feilniu同学.
SQL脚本如下:
DECLARE @BDate datetime, @EDate datetime
SET @BDate = '20150701' --下限
SET @EDate = '20150714 23:59:59' --上限
SELECT id, random_datetime = DATEADD(second,ABS(CHECKSUM(NEWID()))%DATEDIFF(second,@BDate,@Edate),@BDate)
FROM dbo.dt_article
WHERE id BETWEEN 1 AND 100
SET @BDate = '20150701' --下限
SET @EDate = '20150714 23:59:59' --上限
SELECT id, random_datetime = DATEADD(second,ABS(CHECKSUM(NEWID()))%DATEDIFF(second,@BDate,@Edate),@BDate)
FROM dbo.dt_article
WHERE id BETWEEN 1 AND 100
生成的内容为:
id random_datetime
3 2015-07-05 07:55:10.000
4 2015-07-08 06:15:06.000
9 2015-07-12 19:14:24.000
10 2015-07-11 20:13:05.000
12 2015-07-06 19:09:12.000
13 2015-07-09 10:28:59.000
14 2015-07-03 07:18:42.000
15 2015-07-06 09:46:29.000
此时的ID是对应dt_article表中的ID。
然后我们可以先把生成的数据写到临时表中,然后关联更新!
我们修改脚本如下:
SELECT id, random_datetime = DATEADD(second,ABS(CHECKSUM(NEWID()))%DATEDIFF(second,@BDate,@Edate),@BDate)
INTO #Temp
FROM dbo.dt_article
--更新日期
UPDATE dbo.dt_article SET add_time=b.random_datetime
FROM dbo.dt_article a ,#Temp b
WHERE a.id=b.id
INTO #Temp
FROM dbo.dt_article
--更新日期
UPDATE dbo.dt_article SET add_time=b.random_datetime
FROM dbo.dt_article a ,#Temp b
WHERE a.id=b.id