选择范围内的随机数

时间:2013-09-29 10:23:29

标签: sql sql-server random

我有一个带有整数列(ColumnA)的表(TableA),并且表中已有数据。需要编写一个select语句,以便在整数列中插入具有5000以内随机值的整数列。该值不应该已经在TableA的columnA中

Insert into TableA (columnA,<collist....>)

SELECT <newColId> ,<collist....> from TableB <where clause>

1 个答案:

答案 0 :(得分:1)

您可以为此创建一个帮助号码表:

-- create helper numbers table, faster than online recursive CTE
-- can use master..spt_values, but actually numbers table will be useful
-- for other tasks too
create table numbers (n int primary key)

;with cte_numbers as (
    select 1 as n
    union all
    select n + 1 from cte_numbers where n < 5000
)
insert into numbers
select n
from cte_numbers
option (maxrecursion 0);

然后在TableA中插入一些您没有的数字(使用row_number()上的连接,这样您就可以一次插入多行):

;with cte_n as (
    select n.n, row_number() over(order by newid()) as rn
    from numbers as n
    where not exists (select * from tableA as t where t.columnA = n.n)  
), cte_b as (
    select
        columnB, row_number() over(order by newid()) as rn
    from tableB
)
insert into TableA(columnA, columnB)
select n.n, b.ColumnB
from cte_b as b
    inner join cte_n as n on n.rn = b.rn

如果你确定TableB中只有一行会插入,你可以 使用此查询

insert into TableA(columnA, columnB)
select
    a.n, b.columnB
from tableB as b
    outer apply (
        select top 1 n.n
        from numbers as n
        where not exists (select * from tableA as t where t.columnA = n.n)
        order by newid() 
    )  as a

请注意,最好在ColumnA列上设置索引以更快地检查存在。

<强> sql fiddle demo