我有两个表,即Test2和Test3。
我在Test2
表中有10条记录。并且Test3
表中没有记录。
在Test2表中,我在ColumnID
列中有一些空值。
我想通过选择表Test3
AND 中的记录来将记录插入到表Test2
中
值我只想添加最大列ColumnID
加1。
表:Test2
Create table Test2
(
ColumnID int
);
插入:
INSERT INTO Test2 values(1);
INSERT INTO Test2 values(2);
INSERT INTO Test2 values(3);
INSERT INTO Test2 values(5);
INSERT INTO Test2 values(8);
INSERT INTO Test2 values(null);
INSERT INTO Test2 values(null);
INSERT INTO Test2 values(null);
INSERT INTO Test2 values(null);
INSERT INTO Test2 values(null);
预期结果:
表:Test3
ColumnID
----------------
1
2
3
5
8
9 --Increament by 1 to max of id
10 --increment by 1 to max of id
11
12
13
INSERT INTO Test3
SELECT Case WHEN ColumnID IS NOT NULL then ColumnID else max(ColumnID)+1 end as Column_ID
from Test2
group by ColumnID;
DECLARE @count int
DECLARE @i int = 1
SELECT @count = COUNT(*) FROM Test2;
WHILE (@i <= @count)
BEGIN
INSERT INTO Test3
SELECT Case WHEN ColumnID IS NOT NULL then ColumnID else max(ColumnID)+1 end as Column_ID
from Test2
group by ColumnID;
set @i = @i + 1;
END
GO
答案 0 :(得分:3)
试试这个:
INSERT INTO Test3
SELECT COALESCE(ColumnID,
ROW_NUMBER() OVER (PARTITION By ColumnID
ORDER BY ColumnID) +
MAX(ColumnID) OVER ())
FROM Test2