简体   繁体   English

FOR XML在SQL Server中的工作方式

[英]How FOR XML Works in SQL Server

Can somebody explain how is FOR XML used in SQL Server? 有人可以解释一下如何在SQL Server中使用FOR XML吗? Is this the only way to concatenate strings by rows without using an user-defined function? 这是不使用用户定义的函数按行连接字符串的唯一方法吗? I got it from this post , did what I need to do, but I don't understand it. 我从这篇文章中得到了它,做了我需要做的事情,但是我不理解。

The person who posted this did not explain anything. 发布此消息的人没有任何解释。 After an exhaustive search I couldn't find anything understandable. 经过详尽的搜索,我找不到任何可以理解的东西。 And no, MSDN was not helpful given my limited SQL skills. 不,鉴于我的SQL技能有限,MSDN没有帮助。

Here's the my SQL, with only the names changed from the one in that post. 这是我的SQL,只有名称与该帖子中的名称有所不同。

SELECT 
  ID,
  STUFF((
    SELECT ' -' + Code
    FROM #Z 
    WHERE (ID = Results.ID) 
    FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,2,''
 ) AS ConcatCode
FROM #Z Results
GROUP BY ID

Is this the only way to concatenate strings by rows without using an user-defined function? 这是不使用用户定义的函数按行连接字符串的唯一方法吗?

This is the simplest method to concatenate rows 这是连接行的最简单方法

how FOR XML is used in SQL Server 如何在SQL Server中使用FOR XML

I suppose examples below will give more or less clear understanding how use it 我想下面的示例或多或少会清楚地了解如何使用它

------------------------------------------------------------
--Create temp table for testing
IF OBJECT_ID('Tempdb..#Z') IS NOT NULL 
    DROP TABLE #Z
CREATE TABLE #Z
    (
      ID INT ,
      SomeText VARCHAR(3)
    )
INSERT  INTO #Z
        ( ID, SomeText )
VALUES  ( 1, 'AAA' ),
        ( 2, 'BBB' ),
        ( 3, 'CCC' ),
        ( 1, 'ZZZ' ),
        ( 1, 'XXX' ),
        ( 2, 'YYY' )
------------------------------------------------------------
--1. Concatenate
SELECT  SUBSTRING(( SELECT  ',' + SomeText
                    FROM    #Z
                  FOR
                    XML PATH('')
                  ), 2, 1000) AS Concatenated
------------------------------------------------------------
--2. Concatenate for each ID
SELECT DISTINCT
        Z_out.id ,
        SUBSTRING(( SELECT  ',' + SomeText
                    FROM    #Z AS Z_in
                    WHERE   Z_in.ID = Z_out.id
                  FOR
                    XML PATH('')
                  ), 2, 1000) AS Concatenated
FROM    #Z AS Z_out

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM