Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's an alternative</p> <p>Sample table for discussion, don't worry about the nonsensical data, they just need to be null or not</p> <pre><code>create table taddress (id int,a varchar(10),b varchar(10),c varchar(10)); insert taddress select 1,1,2,3 union all select 2,1, null, 3 union all select 3,null, 1, 2 union all select 4,null,null,2 union all select 5,1, null, null union all select 6,null, 4, null </code></pre> <p>The query, which really just normalizes the data</p> <pre><code>;with tmp as ( select *, rn=ROW_NUMBER() over (partition by t.id order by sort) from taddress t outer apply ( select 1, t.a where t.a is not null union all select 2, t.b where t.b is not null union all select 3, t.c where t.c is not null --- EXPAND HERE ) u(sort, line) ) select t0.id, t1.line, t2.line, t3.line from taddress t0 left join tmp t1 on t1.id = t0.id and t1.rn=1 left join tmp t2 on t2.id = t0.id and t2.rn=2 left join tmp t3 on t3.id = t0.id and t3.rn=3 --- AND HERE order by t0.id </code></pre> <h3>EDIT - for the update back into table</h3> <pre><code>;with tmp as ( select *, rn=ROW_NUMBER() over (partition by t.id order by sort) from taddress t outer apply ( select 1, t.a where t.a is not null union all select 2, t.b where t.b is not null union all select 3, t.c where t.c is not null --- EXPAND HERE ) u(sort, line) ) UPDATE taddress set a = t1.line, b = t2.line, c = t3.line from taddress t0 left join tmp t1 on t1.id = t0.id and t1.rn=1 left join tmp t2 on t2.id = t0.id and t2.rn=2 left join tmp t3 on t3.id = t0.id and t3.rn=3 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload