1

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

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

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

1 回答 1

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 中没有的数字(使用 join onrow_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

于 2013-09-29T10:53:01.807 回答