小编典典

将逗号分隔的字符串转换为SQL Server中的多列

sql

我想提取用逗号分隔的特定字符串,并在SQL Server 2008中的特定列之间进行解析。SQLServer中的表结构如下:

CREATE TABLE SAMP(COMMASEPA VARCHAR(255),X VARCHAR(10),Y VARCHAR(10),Z VARCHAR(10),A VARCHAR(10),B VARCHAR(10),C VARCHAR(10),D VARCHAR(10))
INSERT INTO SAMP VALUES('X=1,Y=2,Z=3',null,null,null,null,null,null,null),
('X=3,Y=4,Z=5,A=6',null,null,null,null,null,null,null),
('X=1,Y=2,Z=3,A=5,B=6,C=7,D=8',null,null,null,null,null,null,null)

我希望根据逗号和中的一个字符串来分隔字符串[x/y/z/a/b/c/d]。例如,在第一行的结果表中,X = 1应该在X col中,Y = 2应该在Y
col中,Z = 3应该在Z col中。请输入任何想法。谢谢你。’‘


阅读 349

收藏
2021-03-17

共1个答案

小编典典

您可以在SQL Fiddle上看到此方法:http
://sqlfiddle.com/#!3/8c3ee/ 32

这是它的实质:

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;

全面披露-我是sqlfiddle.com的作者

这是通过首先将每个逗号分隔的字符串转换成如下所示的XML对象来实现的:

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

一旦有了该格式的字符串,便可以使用SQL Server
2005(及更高版本)支持的xquery选项.value('(/root/s/col[@name="X"])[1]', 'varchar(20)')。我分别选择每个可能的列,以便将它们标准化并在可用时进行填充。使用该规范化格式,我用一个称为“已解析”的通用表表达式(CTE)定义了结果集。然后,将此CTE重新加入到update语句中,以便可以在原始表中填充值。

2021-03-17