简体   繁体   中英

How FOR XML Works in SQL Server

Can somebody explain how is FOR XML used in SQL Server? 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.

Here's the my SQL, with only the names changed from the one in that post.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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