1

I have table called Rule.

RuleId    Name
1          A1
2          A2
3          A3
.
.
.

Now I want all the names as single result.

may be like @allnames = A1,A2,A3

Can somebody advise how to write query for this without using loops?

Thanks in advance...

Mahmoud Gamal
  • 75,299
  • 16
  • 132
  • 159
mmssaann
  • 1,457
  • 6
  • 27
  • 53
  • duplicate of http://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string – Rex Sep 02 '13 at 08:29

3 Answers3

5

Try this:

SELECT @allnames = STUFF((SELECT distinct ',' + Name
                      FROM table1
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                        , 1, 1, '');
Mahmoud Gamal
  • 75,299
  • 16
  • 132
  • 159
4
DECLARE @names NVARCHAR(MAX)

SELECT @names = coalesce(@names + ',', '') + coalesce(Name, '') 
FROM (SELECT distinct Name FROM Rule) x

print @names
t-clausen.dk
  • 42,087
  • 11
  • 52
  • 90
3

Try this one -

DECLARE @temp TABLE ([RuleId] INT, Name CHAR(2))
INSERT INTO @temp([RuleId], Name)
VALUES
    (1, 'A1'),
    (2, 'A2'),
    (3, 'A3')

DECLARE @all_names NVARCHAR(MAX)

SELECT @all_names = STUFF((
    SELECT DISTINCT ',' + Name
    FROM @temp
    --ORDER BY Name
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

SELECT @all_names

Output -

---------------
A1,A2,A3
Devart
  • 115,199
  • 22
  • 161
  • 180