Możesz to zobaczyć w SQL Fiddle:http://sqlfiddle.com/#!3/ 8c3ee/32
Oto sedno tego:
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;
Pełne ujawnienie - jestem autorem sqlfiddle.com
Działa to, najpierw konwertując każdy ciąg przecinków na obiekt XML, który wygląda tak:
<root>
<s>
<col name="X">1</col>
</s>
<s>
<col name="Y">2</col>
</s>
....
</root>
Po uzyskaniu ciągu w tym formacie używam opcji xquery obsługiwanych przez SQL Server 2005 (i nowsze), czyli .value('(/root/s/col[@name="X"])[1]', 'varchar(20)')
część. Każdą z potencjalnych kolumn wybieram indywidualnie, więc są one znormalizowane i wypełniane, gdy są dostępne. W tym znormalizowanym formacie definiuję zestaw wyników za pomocą wyrażenia Common Table Expression (CTE), które nazwałem „przeanalizowanym”. To CTE jest następnie łączone z powrotem w instrukcji aktualizacji, dzięki czemu wartości mogą być wypełnione w oryginalnej tabeli.