【问题标题】:Insert specific random values into temp table将特定随机值插入临时表
【发布时间】:2014-06-19 23:57:03
【问题描述】:

我需要为我们数据库中的一个新表创建一些虚拟数据。我将从现有表中获取值,还将创建新列,其中值是从值列表中随机选择的。

我的表结构:

ID -- increment by 1
PersonsID -- will get this values from a different table
Status --Need to insert random values of example "Waived" or "Enrolled"
StatusDate -- need to insert random DateTime within past few months
School --Need to insert random values of example "A", "B", "C", "D"
ChangedBy --Need to insert random username from a different table

有人可以指导我如何在表格中插入随机但特定的值吗?

【问题讨论】:

  • 使用SELECT FROM VALUES() ORDERED BY RAND()

标签: sql sql-server random sql-insert


【解决方案1】:

对于不同类型的随机值,您将需要不同的技术

例如,获取过去 90 天内的随机日期时间。

select dateadd(second, -90*86400*rand(), getdate()) -- 86400 seconds in a day

选择“A”、“B”、“C”或“D”

select substring('ABCD', convert(int,rand()*4+1), 1)

从表 (USStates) 中选择任意值 (StateCode)

select top 1 StateCode from USStates order by newid()

然后你结合这些技术来插入你需要的数据

【讨论】:

  • 注意,如果您通过 newid() 订购并使用 ROW_NUMBER() 您可以加入
【解决方案2】:

如果要获取随机值,SQL中的基本表达式是rand(checksum(newid()))。您可以使用以下方法。

对于id,我假设您有一个带有标识列的新表。这是一个示例查询:

insert into newtable(PersonsID, status, StatusDate, School, ChangedBy)
    select PersonsId,
           (case when rand(checksum(newid())) < 0.5 then 'Waived' else 'Enrolled' end),
           cast(getdate() - 90 * rand(checksum(newid()))),
           (select top 1 col
            from (select 'A' as col union all select 'B' union all select 'C' union all select 'D'
                 ) t
            order by rand(checksum(newid())) 
           ) ,
           (select top 1 username
            from othertable ot
            order by rand(checksum(newid())) 
           )
    from Persons;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2011-08-25
    • 1970-01-01
    • 2014-02-05
    相关资源
    最近更新 更多