Using FOR XML PATH and STUFF SQL String Concatenation

You can use the FOR XML PATH SQL Statement to join or concatenate multiple column values into single row. You could then use STUFF to remove the first ‘,’ (now redundant) after the string has been concatenated.

Create a quick table, listing cities from different countries. You will notice that there are cities that share the same country code:

DECLARE @A_TEMP_TABLE_USED_AS_EXAMPLE TABLE(CountryCode INT, City VARCHAR(50))INSERT @A_TEMP_TABLE_USED_AS_EXAMPLE(CountryCode, City)VALUES(1, 'Johannesburg'), (1, 'Cape Town'), --South Africa(2, 'New York'), (2, 'Washington'), --USA(3, 'Paris') ,(3, 'Nice'), --France(4, 'Rome'), (4, 'Bologna'), --Itlay(5, 'Athens'), (5, 'Volos') --Greece

Add the Following SELECT Query to concatenate the Cities belonging to the same country code onto one line:

--ConcatSELECT DISTINCT 	CountryCode,	STUFF((SELECT ',' + City	FROM @A_TEMP_TABLE_USED_AS_EXAMPLE [TABLE1]	WHERE TABLE1.CountryCode = TABLE2.CountryCode	FOR XML PATH('')), 1, 1,'') 		FROM @A_TEMP_TABLE_USED_AS_EXAMPLE [TABLE2] 

This concatenates all rows with the same country code. STUFF is then used to remove the redundant comma at the start of the row.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet