将VARCHAR列中的XML标签列表转换为逗号分隔列表
我有一个表,其中包含XML标签/值的列表,我需要使用这些列表将其连接到另一个表以检索其实际值并将结果显示为CSV列表。
示例VARCHAR数据:
<choice id="100"/><choice id="101"/><choice id="102"/>
但是,这些值实际上转化为其他值:红色,白色,蓝色。我需要将该列表转换为以下列表:
red,white,blue
作为回顾,“源”表列为VARCHAR,并包含XML属性值的列表,这些值通过将其连接到另一个表来转化为其他值。因此,另一个表具有ID(INT)的主要键,其行为100,101,102。这些行中的每一行分别具有红色,白色,蓝色的值。我希望这足够有意义。
这是设置该方案的DDL:
create table datatable(
id int,
data nvarchar(449)
primary key (id)
);
insert into datatable(id, data)
values(1,'<choice id="100"/><choice id="101"/><choice id="102"/>')
,(2,'<choice id="100"/>')
,(3,'<choice id="101"/>')
,(4,'<choice id="102"/>');
create table choicetable(
id int,
choicevalue nvarchar(449)
primary key (id)
);
insert into choicetable(id, choicevalue)
values(100,'red')
,(101,'white')
,(102,'blue');
这是我第一次尝试以这种方式解析XML,因此我有点想在哪里开始。另外,我无法控制数据库,我正在从(第三方软件)中检索数据。
I have a table that contains a list of xml tags/values that I need to use to join to another table to retrieve their actual value and display the result as a csv list.
Example varchar data:
<choice id="100"/><choice id="101"/><choice id="102"/>
However, these values actually translate to other values: red, white, blue respectively. I need to convert that list to the following list:
red,white,blue
As a recap, the "source" table column is varchar, and contains a list of xml attribute values, and those values translate to other values by joining to another table. So the other table has a primary key of id (int) with rows for 100,101,102. Each of those rows has values red,white,blue respectively. I hope this makes enough sense.
Here is the ddl to set up the scenario:
create table datatable(
id int,
data nvarchar(449)
primary key (id)
);
insert into datatable(id, data)
values(1,'<choice id="100"/><choice id="101"/><choice id="102"/>')
,(2,'<choice id="100"/>')
,(3,'<choice id="101"/>')
,(4,'<choice id="102"/>');
create table choicetable(
id int,
choicevalue nvarchar(449)
primary key (id)
);
insert into choicetable(id, choicevalue)
values(100,'red')
,(101,'white')
,(102,'blue');
This would be the first time I've tried parsing XML in this manner so I'm a little stumped where to start. Also, I do not have control over the database I am retrieving the data from (3rd party software).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有正确的示例数据,就很难给出确切的查询。但是您将执行类似此类
交叉应用
将varchar
转换为xml
.nodes
将XML进入单独的行。.value
加入以获取ID
属性String_agg
加入构造。根据您的情况,您可能不需要 组。我建议您将XML数据存储在
XML
键入列中,如果可能的话。Without proper sample data it's hard to give an exact query. But you would do something like this
CROSS APPLY
to convert thevarchar
toxml
.nodes
to shred the XML into separate rows..value
to get theid
attributeSTRING_AGG
. You may not needGROUP BY
depending on your situation.I would advise you to store XML data in an
xml
typed column if at all possible.