开发者

How to concatenate results in T-SQL into column?

开发者 https://www.devze.com 2023-04-01 08:49 出处:网络
I\'m working on a query which should 开发者_如何学Pythongive me result like: --Name--|--Surname--|--Language--|--Date--|

I'm working on a query which should 开发者_如何学Pythongive me result like:

|--Name--|--Surname--|--Language--|--Date--   | 
| James  |  Hetfield | en,gb,fr   | 2011-01-01|
| Lars   |  Ulrich   | gb,fr,ca   | 2011-01-01|

but my select gets set of rows like:

| James   |  Hetfield    | en   | 2011-01-01|
| James   |  Hetfield    | gb   | 2011-01-01|
| James   |  Hetfield    | fr   | 2011-01-01|
| Lars    |  Ulrich      | gb   | 2011-01-01|
| Lars    |  Ulrich      | fr   | 2011-01-01|
| Lars    |  Ulrich      | ca   | 2011-01-01|

Which best method you recommend to convert sets of result into coma-separated values in grouped column 'on the fly'? I've found that CROSS APPLY could do the work but people says that this method is very consuming. As an addition DB has huge amount of data.

Thanks in advance, Regards, Adrian


here is the best concatenation method, it will not expand special characters like other XML methods:

--Concatenation with FOR XML & eliminating control/encoded char expansion "& < >"
set nocount on;
declare @YourTable table (RowID int, HeaderValue int, ChildValue varchar(5))
insert into @YourTable VALUES (1,1,'CCC')
insert into @YourTable VALUES (2,2,'B<&>B')
insert into @YourTable VALUES (3,2,'AAA')
insert into @YourTable VALUES (4,3,'<br>')
insert into @YourTable VALUES (5,3,'A & Z')
set nocount off
SELECT
    t1.HeaderValue
        ,STUFF(
                   (SELECT
                        ', ' + t2.ChildValue
                        FROM @YourTable t2
                        WHERE t1.HeaderValue=t2.HeaderValue
                        ORDER BY t2.ChildValue
                        FOR XML PATH(''), TYPE
                   ).value('.','varchar(max)')
                   ,1,2, ''
              ) AS ChildValues
    FROM @YourTable t1
    GROUP BY t1.HeaderValue

OUTPUT:

HeaderValue ChildValues
----------- ---------------
1           CCC
2           AAA, B<&>B
3           <br>, A & Z

(3 row(s) affected)


If your version of SQL supports FOR XML use

select n.[name],CONVERT(VARCHAR(MAX),(SELECT *
        FROM (
                SELECT  l.[lang] + ' , '  AS '*'
                FROM    tblLang l
                WHERE l.[name]=n.[name]
                ) x
        FOR XML PATH (''), TYPE
    )) AS [Language]

from tblName n 

This assumes simple table like

tblName
-------
name VARCHAR

tblLang
-------
lang VARCHAR
name VARCHAR

and it also adds a trailing , :(

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号