我有一个表,其主键是正整数:
CREATE TABLE T
(
ID int PRIMARY KEY CHECK (ID > 0) -- not an IDENTITY column
-- ... other irrelevant columns...
)
给定一个正整数 N ,我想插入ID为1- N 的 N 记录。但是,如果已存在具有特定ID的记录,我想改为插入下一个最高的未使用ID。例如, N = 5:
If the table contains... Then insert...
(Nothing) 1,2,3,4,5
1,2,3 4,5,6,7,8
3,6,9,12 1,2,4,5,7
这是一种天真的方式:
DECLARE @N int = 5 -- number of records to insert
DECLARE @ID int = 1 -- next candidate ID
WHILE @N > 0 -- repeat N times
BEGIN
WHILE EXISTS(SELECT * FROM T WHERE ID = @ID) -- conflicting record?
SET @ID = @ID + 1
INSERT T VALUES (@ID)
SET @ID = @ID + 1
SET @N = @N - 1
END
但如果 E 是现有记录的数量,那么在最坏的情况下,此代码执行 E + N SELECTs和 N INSERT,这是非常低效的。
是否有一种智能方法可以使用少量SELECT和一个INSERT执行此任务?
答案 0 :(得分:3)
您可以使用计数表和NOT IN
我想......
WITH
E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
)
select N into #temp from cteTally
declare @table table (i int)
insert into @table
values
(3),
(6),
(9),
(12)
insert into @table
select top 5 N from #temp where N not in (select i from @table) order by N
select * from @table
drop table #temp
信用@SeanLange强调统计表并最初显示我
答案 1 :(得分:0)
试试这个;
insert into T
select top 5
[ID]
from
(
select
[ID]=RANK()over(order by [ID])+5
from
T
union
select [ID]=1 union
select [ID]=2 union
select [ID]=3 union
select [ID]=4 union
select [ID]=5
)IDs
where
not exists(select 1 from T data where data.ID=IDs.ID)
不需要临时表,可能更容易阅读和维护(很乐意纠正:))