sql >> Base de Datos >  >> RDS >> Sqlserver

Convertir una cadena delimitada por comas en varias columnas en el servidor sql

Puede ver esto funcionando en SQL Fiddle:http://sqlfiddle.com/#!3/ 8c3ee/32

Aquí está el meollo:

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;

Divulgación completa:soy el autor de sqlfiddle.com

Esto funciona convirtiendo primero cada cadena commasepa en un objeto XML que se ve así:

<root>
 <s>
  <col name="X">1</col>
 </s>
 <s>
  <col name="Y">2</col>
 </s>
  ....
</root>

Una vez que tengo la cadena en ese formato, uso las opciones de consulta que admite SQL Server 2005 (y versiones posteriores), que es .value('(/root/s/col[@name="X"])[1]', 'varchar(20)') parte. Selecciono cada una de las columnas potenciales individualmente, para que se normalicen y completen cuando estén disponibles. Con ese formato normalizado, defino el conjunto de resultados con una expresión de tabla común (CTE) que llamé 'analizado'. Este CTE luego se vuelve a unir en la declaración de actualización, de modo que los valores se puedan completar en la tabla original.