UPDATE如果column不为null,如果为null则保留为null

时间:2012-08-27 09:10:56

标签: sql-server tsql

我有以下SQL:

UPDATE TableA
SET first_name = 'AAA',
    last_name = 'BBB',
    address1 = '123',
    address2 = 'Fake St.,',
    phone = '1234567',
    id = '11223344'

如果每列都不为空,我应该使用什么才能更新?

2 个答案:

答案 0 :(得分:30)

update tableA
set first_name = case when first_name is null then null else 'aaa' end,
last_name = case when last_name is null then null else 'bbb' end,
...

答案 1 :(得分:1)

另一种不那么冗长(不太可读)的方法:

UPDATE TableA
SET first_name = left(  'AAA' + first_name, 3 )  ,
    last_name = left(  'BBB' + last_name, 3 )  ,
    address1 = left(  '123' + address1, 3 )  ,
    address2 = left(  'Fake St.,' + address2, len( 'Fake St.,' ) )  ,
    ...