[英]Extract comma separated values from comma separated GUIDs
I have a column in table T1
named Categories
, which contains GUIDs in XML.我在表
T1
中有一个名为Categories
的列,其中包含 XML 中的 GUID。 I am able to extract the GUIDs in a comma-separated form using the below query.我可以使用以下查询以逗号分隔的形式提取 GUID。
SELECT
Row, ID, Name, City,
Category = STUFF(
(
SELECT ',' + t.c.value('.', 'nvarchar(max)')
FROM dbo.T1 t1
OUTER APPLY t1.Categories.nodes('root/string') as t(c)
WHERE t1.ID = t2.ID FOR XML PATH('')
), 1, 1, ''
)
FROM
dbo.T1 t2
I have another table T2
, which contains the names of the Categories.我有另一个表
T2
,其中包含类别的名称。 I now want to use these comma-separated GUIDs to go and fetch their corresponding Name
from T2
.我现在想将这些逗号分隔的 GUID 用于 go 并从
T2
获取它们对应的Name
。
What changes do I need to make in my SELECT statement to write a LEFT OUTER JOIN which takes this comma-separated GUIDs and returns comma-separated names from T2
.我需要在我的 SELECT 语句中进行哪些更改以编写一个 LEFT OUTER JOIN ,它采用这个逗号分隔的 GUID 并从
T2
返回逗号分隔的名称。
T2
looks something like this: T2
看起来像这样:
I would join the category name table before concatenating the values to avoid another iteration of splitting and concatenating.我会在连接值之前加入类别名称表,以避免再次进行拆分和连接迭代。
Sample data样本数据
create table xmlData
(
id int,
data xml
);
insert into xmlData (id, data) values
(1,'
<root>
<guid>5d8547aa-e1e7-4f69-88a2-655879531582</guid>
<guid>78555c5d-e39f-48f3-a148-30161b0fb995</guid>
</root>
'),
(2,'
<root>
<guid>5d8547aa-e1e7-4f69-88a2-655879531582</guid>
<guid>f58177f6-63c8-4985-baa8-2db05248f13f</guid>
</root>
'),
(3,'
<root>
<guid>5d8547aa-e1e7-4f69-88a2-655879531582</guid>
<guid>d8f9b789-6d60-4688-9d91-c0f8b1df5319</guid>
</root>
');
create table categoryName
(
guid uniqueidentifier,
name nvarchar(20)
);
insert into categoryName (guid, name) values
('5d8547aa-e1e7-4f69-88a2-655879531582', 'Alpha'),
('78555c5d-e39f-48f3-a148-30161b0fb995', 'Beta'),
('f58177f6-63c8-4985-baa8-2db05248f13f', 'Gamma'),
('d8f9b789-6d60-4688-9d91-c0f8b1df5319', 'Delta');
Solution解决方案
Two versions because the SQL Server version is not specified in the question tags... The string_agg()
function is available starting from SQL Server 2017.两个版本,因为 SQL 服务器版本未在问题标签中指定...
string_agg()
function 从 Z9778840A0100CB30C9828767417B0B5A2Z 服务器开始可用。20
With string_agg()
使用
string_agg()
select xd.id,
string_agg(cn.name, ',') as 'category_names'
from xmlData xd
cross apply xd.data.nodes('root/guid') g(guid)
join categoryName cn
on cn.guid = g.guid.value('.', 'nvarchar(36)')
group by xd.id
order by xd.id;
Without string_agg()
没有
string_agg()
select xd.id,
stuff( ( select ',' + cn.name
from xmlData xd2
cross apply xd.data.nodes('root/guid') g(guid)
join categoryName cn
on cn.guid = g.guid.value('.', 'nvarchar(36)')
where xd2.id = xd.id
for xml path('') ), 1, 1, '' ) as 'category_names'
from xmlData xd
order by xd.id;
Result结果
id category_names
-- --------------
1 Alpha,Beta
2 Alpha,Gamma
3 Alpha,Delta
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.