SQL SERVER Replace Null

If the values are increasing, use a cumulative max:

select t.*,
       max(code) over (order by id) as imputed_code
from @table t;

If the code is not strictly increasing, then you can do this in two steps:

select t.*, max(code) over (order by grp) as imputed_code
from (select t.*,
             count(code) over (order by id) as grp
      from @table t
     ) t;

Given that this is a table variable, I’m guessing that you don’t really want to update it. But if you do:

with toupdate as (
      <one of the above queries>
     )
update toupdate
    set code = imputed_code
    where code is null;

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top