Wednesday, 11 December 2013

MSSQL - Simple GROUP_CONCAT

The simple and compact form of GROUP_CONCAT functionality in SQL Server.

Re-Creates table with test strings:
  1. -- Re-Create and fill table with test strings
  2. IF OBJECT_ID('dbo.TestTexts') IS NOT NULL
  3. DROP TABLE dbo.TestTexts;
  4. GO
  5. CREATE TABLE dbo.TestTexts (SomeText VARCHAR(20));
  6. GO
  7. INSERT INTO dbo.TestTexts
  8. VALUES
  9. ('Aaa'),
  10. ('Bbb'),
  11. ('Ccc'),
  12. ('Ddd');
  13. GO

Simple concatination of strings:
  1. SELECT GROUP_CONCAT = '' + (
  2. SELECT '' + SomeText
  3. FROM dbo.TestTexts
  4. ORDER BY SomeText
  5. FOR XML PATH('')
  6. )
Query Result:

GROUP_CONCAT
------------
AaaBbbCccDdd


Concatinates Strings with delimiter:
  1. SELECT
  2. -- Remove First Comma
  3. GROUP_CONCAT = STUFF(
  4. (
  5. -- Concatinate Strings
  6. SELECT ',' + SomeText
  7. FROM dbo.TestTexts
  8. ORDER BY SomeText
  9. FOR XML PATH('')
  10. ),
  11. 1,1,''
  12. );
  13. GO
Query Result:

GROUP_CONCAT
---------------
Aaa,Bbb,Ccc,Ddd