仅当其他列不为NULL时才复制列值

时间:2014-05-05 07:00:48

标签: sql sql-server

我在接受采访时被问到以下类型的输出:

Id  A       B        C
1   a       b      (insert value of B) 
2   a      NULL    (insert value of A)
3 NULL     NULL    (insert 'X')

我在SQL中有点新功能,我正在尝试这个,但到目前为止还没有正确实现它。这就是我所拥有的:

IF EXISTS(select * from #tbl where A IS NOT NULL) 
    IF EXISTS(select * from #tbl where B is not null)
        UPDATE #tbl SET C =B
    ELSE
        UPDATE #tbl SET C =A
ELSE
    IF EXISTS(select * from #tbl where B IS NULL)
    UPDATE #tbl SET C ='X'

我还想删除“else”是否有更好的方法来做到这一点?

4 个答案:

答案 0 :(得分:4)

完成coalesce运算符是为了找到“next not null value”。

update #tbl
set C = coalesce(B, A, 'X')

假设B,A是Varchar或同化......

答案 1 :(得分:0)

将case语句与isnull一起使用。有点像:

update #tbl
set C = 
case 
    when A is not null THEN  A
    when B is not null THEN  B
    else                     'X'
end

答案 2 :(得分:0)

有三次更新

update table set c = 'X' where a is null and b is null and c is null
update table set c = b where (not a is null) and not (b is null) and c is null
update table set c = a where (not a is null) and b is null and c is null

答案 3 :(得分:0)

使用ISNULL:

update tbl 
set C=
ISNULL(ISNULL(B, A), 'X')

使用案例

update tbl
set C = 
case 
    when A is not null and B IS not null THEN  B
    when A is not null and B IS null THEN  A
    else 'X'
end