如何使用随机日期更新行 [英] How to update rows with a random date
问题描述
我有一个简单的 SQL 表,它有一个 DateTime 列.我想用随机日期更新所有行(> 100000 行).有没有一种简单的方法来执行 SQL 查询?
I have a simple SQL table which has a DateTime column. I would like to update all the rows (>100000 rows) with a random date. Is there a simple way to do this a SQL Query?
推荐答案
使用它来生成 1900 年 1 月 1 日至 2079 年 6 月 6 日之间的小日期时间(未选中,未安装 SQL)
Use this to generate a smalldatetime between 01 Jan 1900 and 06 Jun 2079 (not checked, SQL not installed)
DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0)
NEWID 比尝试使用 RAND 更好:RAND 不会在单个 SELECT 或 UPDATE 中生成不同值的行(在 SQL 2000 中不会,以防行为发生变化).
NEWID is better then trying to use RAND: RAND does not generate different values row in a single SELECT or UPDATE (well it didn't in SQL 2000, in case behaviour has changed).
像这样
UPDATE
table
SET
datetimecol = DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0)
将 65535 改为 65530 并添加 ABS 以避免在范围上限溢出
changed 65535 to 65530 and added ABS to avoid overflow at upper limit of range
这篇关于如何使用随机日期更新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!