Stuff 和“For Xml Path"如何在 SQL Server 中工作? [英] How Stuff and 'For Xml Path' work in SQL Server?

查看:23
本文介绍了Stuff 和“For Xml Path"如何在 SQL Server 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

表格是:

<头>
ID姓名
1aaa
1bbb
1抄送
1ddd
1ee

所需输出:

<头>
IDabc
1aaa,bbb,ccc,ddd,eee

查询:

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.

推荐答案

这是它的工作原理:

1.使用 FOR XML 获取 XML 元素字符串

在查询末尾添加 FOR XML PATH 允许您将查询结果作为 XML 元素输出,元素名称包含在 PATH 参数中.例如,如果我们要运行以下语句:

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 ('')

通过传入一个空白字符串 (FOR XML PATH('')),我们得到以下结果:

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

,aaa,bbb,ccc,ddd,eee

2.用 STUFF 删除前导逗号

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

STUFF 的参数为:

  • 要填充"的字符串(在我们的例子中是名称的完整列表,带有前导逗号)
  • 开始删除和插入字符的位置(1,我们正在填充一个空白字符串)
  • 要删除的字符数(1,作为前导逗号)

所以我们最终得到:

aaa,bbb,ccc,ddd,eee

3.加入 id 以获取完整列表

接下来我们只需将其加入临时表中的 id 列表,以获取带有名称的 ID 列表:

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;

我们得到了结果:

<头>
ID姓名
1aaa,bbb,ccc,ddd,eee

希望这会有所帮助!

这篇关于Stuff 和“For Xml Path"如何在 SQL Server 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆