Sql 在临时表中插入特定的随机值
我需要为数据库中的一个新表创建一些虚拟数据。我将从现有的表中获取值,并将创建新的列,其中的值是从值列表中随机选择的 我的表格结构:Sql 在临时表中插入特定的随机值,sql,sql-server,random,sql-insert,Sql,Sql Server,Random,Sql Insert,我需要为数据库中的一个新表创建一些虚拟数据。我将从现有的表中获取值,并将创建新的列,其中的值是从值列表中随机选择的 我的表格结构: 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 rando
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
有人能指导我如何在表中插入随机但特定的值吗?对于不同类型的随机值,您需要不同的技术 例如,获取过去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()
然后结合这些技术插入所需的数据如果要获得随机值,SQL中的基本表达式是randchecksumnewid。以下是您可能使用的方法 对于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;
使用从RANDnote排序的值中选择,如果您按newid排序并使用ROW_NUMBER,则可以进行联接