Anda dapat melihat ini bekerja di SQL Fiddle:http://sqlfiddle.com/#!3/ 8c3ee/32
Ini dia dagingnya:
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;
Pengungkapan penuh - Saya penulis sqlfiddle.com
Ini bekerja dengan terlebih dahulu mengubah setiap string koma menjadi objek XML yang terlihat seperti ini:
<root>
<s>
<col name="X">1</col>
</s>
<s>
<col name="Y">2</col>
</s>
....
</root>
Setelah saya memiliki string dalam format itu, saya kemudian menggunakan opsi xquery yang didukung SQL Server 2005 (dan lebih tinggi), yaitu .value('(/root/s/col[@name="X"])[1]', 'varchar(20)')
bagian. Saya memilih masing-masing kolom potensial satu per satu, sehingga kolom tersebut dinormalisasi dan diisi jika tersedia. Dengan format yang dinormalisasi itu, saya mendefinisikan hasil yang ditetapkan dengan Common Table Expression (CTE) yang saya sebut 'parsing'. CTE ini kemudian digabungkan kembali dalam pernyataan pembaruan, sehingga nilai dapat diisi di tabel asli.