Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

How to Implement GROUP_CONCAT in SQL SERVER

0.00/5 (No votes)
19 Feb 2016CPOL 21K  
This tip aims to demonstrate in a simple way how to implement MySQL GROUP_CONCAT function in SQL SERVER.

Introduction

Imagine that we want to return a list of products from a store in a query only. Is it possible? For example, what returns the attribute 'products' as follows: video games, cd, dvd, chair.

In MySQL, it's simple, you just call the GROUP_CONCAT function.

But in SQL SERVER, it is a little more complicated. To do this, one must do the following:

Content

Consider the following table structure:

SQL
CREATE TABLE store(
id INTEGER,
name varchar(50)

)

CREATE TABLE product(
id INTEGER,
id_store INTEGER
name VARCHAR(10),
price FLOAT
)

Now, let's perform some inserts:

SQL
INSERT INTO store VALUES(1,'CARREFULL');

INSERT INTO product VALUES (1,1,'videogame',2.00);
INSERT INTO product VALUES (2,1,'cd',3.00);
INSERT INTO product VALUES (3,1,'dvd',4.00);
INSERT INTO product VALUES (4,1,'table',5.00);

Creating a temporary table (this may vary depending on the used SGBD) with product data.

SQL
SELECT product.name,
Values1 = CAST(NULL AS VARCHAR(8000))
INTO #teste
FROM product
WHERE product.id_store = '1'

Update to go through all the records from the temporary table.

SQL
/* Creating variables */
DECLARE

    @retorno VARCHAR(8000),

    @Values1 varchar(8000)

/* setting default value for the variable @Values1 */
SET @Values1 = ''

/* Performing an update on the temporary #teste table to scroll through all the records,
and thus be able to add the name of each variable product will @Values1 */

UPDATE #teste
    SET Values1 = nome,

    @Values1 =  @Values1  + name + ','

/* conditionally setting the value of the variable @retorno
as equivalent to the value of the variable @Values1 */
if     @Values1 = ''

    SET @retorno = '-'

else

    SET @retorno = @Values1

In query, we decided that the list of product names separated by commas, will be in the column 'product'.

SQL
select loja.*,products=@retorno from store WHERE id = 1;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)