Stuff 和“用于 Xml 路径"如何在 SQL Server 中工作?

编程入门 行业动态 更新时间:2024-10-28 04:18:46
本文介绍了Stuff 和“用于 Xml 路径"如何在 SQL Server 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Table is:

Id Name
1 aaa
1 bbb
1 ccc
1 ddd
1 eee

Required output:

Id abc
1 aaa,bbb,ccc,ddd,eee

Query:

SELECT ID, abc = STUFF( (SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, '' ) FROM temp1 GROUP BY id

This query is working properly. But I just need the explanation how it works or is there any other or short way to do this.

I am getting very confused to understand this.

解决方案

Here is how it works:

1. Get XML element string with FOR XML

Adding FOR XML PATH to the end of a query allows you to output the results of the query as XML elements, with the element name contained in the PATH argument. For example, if we were to run the following statement:

SELECT ',' + name FROM temp1 FOR XML PATH ('')

By passing in a blank string (FOR XML PATH('')), we get the following instead:

,aaa,bbb,ccc,ddd,eee

2. Remove leading comma with STUFF

The STUFF statement literally "stuffs" one string into another, replacing characters within the first string. We, however, are using it simply to remove the first character of the resultant list of values.

SELECT abc = STUFF(( SELECT ',' + NAME FROM temp1 FOR XML PATH('') ), 1, 1, '') FROM temp1

The parameters of STUFF are:

  • The string to be "stuffed" (in our case the full list of name with a leading comma)
  • The location to start deleting and inserting characters (1, we’re stuffing into a blank string)
  • The number of characters to delete (1, being the leading comma)

So we end up with:

aaa,bbb,ccc,ddd,eee

3. Join on id to get full list

Next we just join this on the list of id in the temp table, to get a list of IDs with name:

SELECT ID, abc = STUFF( (SELECT ',' + name FROM temp1 t1 WHERE t1.id = t2.id FOR XML PATH ('')) , 1, 1, '') from temp1 t2 group by id;

And we have our result:

Id Name
1 aaa,bbb,ccc,ddd,eee

更多推荐

Stuff 和“用于 Xml 路径"如何在 SQL Server 中工作?

本文发布于:2023-10-19 00:09:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1505835.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   如何在   工作   Xml   Stuff

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!