Je kunt dit zien werken op SQL Fiddle:http://sqlfiddle.com/#!3/ 8c3ee/32
Hier is het vlees van:
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;
Volledige openbaarmaking - ik ben de auteur van sqlfiddle.com
Dit werkt door eerst elke commasepa-tekenreeks te converteren naar een XML-object dat er als volgt uitziet:
<root>
<s>
<col name="X">1</col>
</s>
<s>
<col name="Y">2</col>
</s>
....
</root>
Zodra ik de string in die indeling heb, gebruik ik de xquery-opties die SQL Server 2005 (en hoger) ondersteunen, namelijk de .value('(/root/s/col[@name="X"])[1]', 'varchar(20)')
een deel. Ik selecteer elk van de potentiële kolommen afzonderlijk, zodat ze worden genormaliseerd en ingevuld indien beschikbaar. Met dat genormaliseerde formaat definieer ik de resultatenset met een Common Table Expression (CTE) die ik 'parsed' noemde. Deze CTE wordt vervolgens weer samengevoegd in de update-instructie, zodat de waarden in de oorspronkelijke tabel kunnen worden ingevuld.