Můžete vidět, jak to funguje na SQL Fiddle:http://sqlfiddle.com/#!3/ 8c3ee/32
Tady je maso z toho:
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;
Úplné zveřejnění – jsem autorem webu sqlfiddle.com
Funguje to tak, že nejprve převedete každý řetězec commasepa na objekt XML, který vypadá takto:
<root>
<s>
<col name="X">1</col>
</s>
<s>
<col name="Y">2</col>
</s>
....
</root>
Jakmile mám řetězec v tomto formátu, použiji možnosti xquery, které podporuje SQL Server 2005 (a vyšší), což je .value('(/root/s/col[@name="X"])[1]', 'varchar(20)')
část. Vybírám každý z potenciálních sloupců jednotlivě, takže jsou normalizovány a naplněny, když jsou k dispozici. S tímto normalizovaným formátem definuji sadu výsledků pomocí společného tabulkového výrazu (CTE), který jsem nazval „analyzovaný“. Tento CTE je pak připojen zpět do příkazu aktualizace, takže hodnoty mohou být naplněny v původní tabulce.