Você pode ver isso funcionando no SQL Fiddle:http://sqlfiddle.com/#!3/ 8c3ee/32
Aqui está a carne dele:
with parsed as (
select
commasepa,
root.value('(/root/s/col[@name="X"])[1]', 'varchar(20)') as X,
root.value('(/root/s/col[@name="Y"])[1]', 'varchar(20)') as Y,
root.value('(/root/s/col[@name="Z"])[1]', 'varchar(20)') as Z,
root.value('(/root/s/col[@name="A"])[1]', 'varchar(20)') as A,
root.value('(/root/s/col[@name="B"])[1]', 'varchar(20)') as B,
root.value('(/root/s/col[@name="C"])[1]', 'varchar(20)') as C,
root.value('(/root/s/col[@name="D"])[1]', 'varchar(20)') as D
FROM
(
select
commasepa,
CONVERT(xml,'<root><s><col name="' + REPLACE(REPLACE(COMMASEPA, '=', '">'),',','</col></s><s><col name="') + '</col></s></root>') as root
FROM
samp
) xml
)
update
samp
set
samp.x = parsed.x,
samp.y = parsed.y,
samp.z = parsed.z,
samp.a = parsed.a,
samp.b = parsed.b,
samp.c = parsed.c,
samp.d = parsed.d
from
parsed
where
parsed.commasepa = samp.commasepa;
Divulgação completa - sou o autor de sqlfiddle.com
Isso funciona primeiro convertendo cada string commasepa em um objeto XML que se parece com isso:
<root>
<s>
<col name="X">1</col>
</s>
<s>
<col name="Y">2</col>
</s>
....
</root>
Depois de ter a string nesse formato, uso as opções xquery que o SQL Server 2005 (e superior) suporta, que é o
.value('(/root/s/col[@name="X"])[1]', 'varchar(20)')
papel. Eu seleciono cada uma das colunas potenciais individualmente, para que sejam normalizadas e preenchidas quando disponíveis. Com esse formato normalizado, defino o conjunto de resultados com uma expressão de tabela comum (CTE) que chamei de 'analisada'. Esse CTE é então associado novamente na instrução de atualização, para que os valores possam ser preenchidos na tabela original.