简体   繁体   English

将特定的随机值插入临时表

[英]Insert specific random values into temp table

I need to create some dummy data for one of the new tables in our database. 我需要为数据库中的新表之一创建一些虚拟数据。 I will be getting values from existing tables and also will be creating new columns in which values are randomly chosen from a list of values. 我将从现有的表中获取值,还将创建新的列,其中从值列表中随机选择值。

My table structure: 我的表结构:

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

Can someone guide me regarding how to insert random, but specific values in a table? 有人可以指导我如何在表格中插入随机但特定的值吗?

You will need different techniques for different types of randomized values 对于不同类型的随机值,您将需要不同的技术

For example, to get random datetime within past 90 days. 例如,要获取过去90天内的随机日期时间。

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

To select 'A','B','C', or 'D' 要选择“ A”,“ B”,“ C”或“ D”

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

To select an arbitrary value (StateCode) from a table (USStates) 从表(USStates)中选择一个任意值(StateCode)

select top 1 StateCode from USStates order by newid()

Then you combine these techniques to insert the data your need 然后,您可以结合使用这些技术来插入所需的数据

If you want to get random values, the basic expression in SQL is rand(checksum(newid())) . 如果要获取随机值,则SQL中的基本表达式是rand(checksum(newid())) Here are ways you might use this. 您可以通过以下方式使用它。

For the id , I will assume you have a new table with an identity column. 对于id ,我假设您有一个带有标识列的新表。 Here is an example query: 这是查询示例:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM