2017-02-17 168 views
1

我有兩個表,即Test2和Test3。SQL Server:當NULL時添加max(column_value)+1

我在Test2表中有10條記錄。並且在Test3表中沒有記錄。

在Test2表中,我在列ColumnID列中有一些空值。

我想從表Test2選擇記錄將記錄插入到表Test3當出現空 值我只是想和最大添加它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 
+0

哪個版本的SQL Server使用的是? – Sankar

+0

當您從** Test2 **選擇記錄添加到** Test3 **時,您的問題需要添加'ORDER'邏輯。如果您添加的順序爲'1,null,3,null,5',則結果將與'null,null,1,3,5'不同。 –

+0

@SankarRaj,2008 R2 – MAK

回答

3

試試這個:

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

Demo here