基于列条件更新表中的行

时间:2017-12-03 15:43:04

标签: sql sql-server

我有以下要求,如果gwtypelist中存在,则使用table_name列更新gwtypelist列的NULL值

    table_name          typecode    gwtypelist           gwtypecode
cctl_banlength_ext  13to24months    cctl_banlength_ext  13to24months
cctl_banlength_ext  25to36months    cctl_banlength_ext  25to36months
cctl_banlength_ext  37to48months    cctl_banlength_ext  37to48months
cctl_banlength_ext  49to60months    cctl_banlength_ext  49to60months
cctl_banlength_ext  6to12months     cctl_banlength_ext  6to12months
cctl_banlength_ext  lessthan6months cctl_banlength_ext  lessthan6months
cctl_banlength_ext  morethan60months       NULL         NULL
cctl_country            UK             cctl_country     UK
cctl_country        Australia             NULL          NULL
cctl_vehicle        Audi                  NULL          NULL
cctl_vehicle        Masserati             NULL          NULL

输出:如果第三列的NULL值存在于第一列中,则应填充第三列

    table_name          typecode    gwtypelist           gwtypecode
cctl_banlength_ext  13to24months    cctl_banlength_ext  13to24months
cctl_banlength_ext  25to36months    cctl_banlength_ext  25to36months
cctl_banlength_ext  37to48months    cctl_banlength_ext  37to48months
cctl_banlength_ext  49to60months    cctl_banlength_ext  49to60months
cctl_banlength_ext  6to12months     cctl_banlength_ext  6to12months
cctl_banlength_ext  lessthan6months cctl_banlength_ext  lessthan6months
cctl_banlength_ext  morethan60months cctl_banlength_ext NULL
cctl_country            UK             cctl_country     UK
cctl_country        Australia          cctl_country     NULL
cctl_vehicle        Audi                  NULL          NULL
cctl_vehicle        Masserati             NULL          NULL

我尝试运行一些更新查询,但我总是得到相同的结果。

update #comp
set gwtypelist = table_name
where gwtypelist in (select distinct table_name from #comp)

如果可以使用更新声明或其他替代方法,请告知我们。

1 个答案:

答案 0 :(得分:1)

我认为这可以满足您的需求:

update c
    set gwtypelist = c.table_name
    from #comp c
    where c.gwtypelist is null and
          exists (select 1 from #comp c2 where c2.gwtypelist = c.table_name);