2013-09-29 69 views
1

我有一個表(TableA)與一個整數列(ColumnA),並且表中有數據。需要編寫一個查詢語句來插入此表中5000具有隨機值的整數列,此值不應該已經在columnA表A的選擇一個範圍內的隨機數

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

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

我希望這篇[文章](http://www.sqlperformance.com/2013/09/t-sql-queries/random-collisions)幫助。 –

回答

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 

如果喲你就像確定,有可能是從表B將被插入只有一行,您可以 使用此查詢

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

+0

我懷疑你的嵌套子查詢會隨着數據量的增加而對性能產生負面影響。 –

+0

我真的認爲在性能上沒有差別(或者左連接會更糟),你有任何測試嗎? –

+0

請參閱:http://stackoverflow.com/a/2577224/1688441。我可能是錯的,但這是一個需要解決的相關問題。 –