Du kan se dette arbejde på SQL Fiddle:http://sqlfiddle.com/#!3/ 8c3ee/32
Her er kødet af det:
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;
Fuld offentliggørelse - jeg er forfatteren af sqlfiddle.com
Dette virker ved først at konvertere hver komma-streng til et XML-objekt, der ser sådan ud:
<root>
<s>
<col name="X">1</col>
</s>
<s>
<col name="Y">2</col>
</s>
....
</root>
Når jeg har strengen i det format, bruger jeg så de xquery-indstillinger, som SQL Server 2005 (og opefter) understøtter, som er .value('(/root/s/col[@name="X"])[1]', 'varchar(20)')
en del. Jeg vælger hver af de potentielle kolonner individuelt, så de normaliseres og udfyldes, når de er tilgængelige. Med det normaliserede format definerer jeg resultatsættet med et Common Table Expression (CTE), som jeg kaldte 'parsed'. Denne CTE sammenføjes derefter i opdateringssætningen, så værdierne kan udfyldes i den oprindelige tabel.