2

Can something like this be done with a select statement:

SELECT col1, concat(col2 + ' ') FROM ....
       GROUP BY col1

I know i can use count(col2) or sum(col2) for integers but is there a function for concatenating if the type is nvarchar or nchar?

2
  • 1
    Yes, but depends on which RDBMS you are using. Commented Dec 5, 2009 at 11:11
  • Forgot to mention that i am using Microsoft SQL server 2008. Commented Dec 5, 2009 at 11:15

3 Answers 3

4

In SQL Server, if you want to concatenate across rows, there is no built in function to do this.

I personally like using XML PATH as it seems to perform well, but this will work only in SQL Server 2005 onwards

SELECT
  STUFF(
    (
    SELECT
      ' ' + Description
    FROM dbo.Brands
    FOR XML PATH('')
    ), 1, 1, ''
  ) As concatenated_string
Sign up to request clarification or add additional context in comments.

2 Comments

Tried it out and it works as i need i to. Thanks for the help :).
No problem, happy to help. Depending on the query, you may need to bind the resultset that is concatenated inside the STUFF function to a field outside of the function using a join, in order to restrict the resultset and hence concatenated string for each result in an outer resultset.
1

The + operator is used to concatenate strings in T-SQL.

EDIT:

If you wish to aggregate strings over multiple rows this might help.

1 Comment

The OP wants a Group By aggregate function to do this.
0

Using Sql Server there is no built-in aggregate concatenation foncton, I know MySql has one called group_concat.

Sql Server, you, would either have to write your own scaler funcion, or a CLR function to achieve this.

Or you can use a cursor to do this for you, with a table var to return the results. I can provide an example if you like.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.