Friday, March 27, 2009

Using COALESCE to create delimited strings in SQL Server

According to MSDN, COALESCE returns the first non-null expression among its arguments. Returns the data type of expression with the highest data type precedence. At least one of the null values must be a typed NULL.

Using COALESCE to create delimited strings :

We have a table tbl_mst_country

SELECT * FROM tbl_mst_country

Result :

ID  Country
===========
1  UAE
2  EGY
3  KSA

Now we want to generate a string containing all the country id delimited by ";".

DECLARE @delimitedIDs varchar(20)
SELECT @delimitedIDs = COALESCE(@delimitedIDs + '; ', '') + CONVERT(VARCHAR(3),pk_intcountryid)
FROM tbl_mst_country
SELECT @delimitedIDs

Result :

1; 2; 3; 4; 5; 6; 7;

No comments:

Post a Comment