SQL Server:NULL时添加max(column_value)+1

时间:2017-02-17 07:50:50

标签: sql sql-server

我有两个表,即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

尝试:1

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;

尝试:2

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

1 个答案:

答案 0 :(得分:3)

试试这个:

INSERT INTO Test3
SELECT COALESCE(ColumnID, 
                ROW_NUMBER() OVER (PARTITION By ColumnID 
                                   ORDER BY ColumnID) +  
                MAX(ColumnID) OVER ()) 
FROM Test2 

Demo here