IntroductionIts very often to convert a database table to comma delimited string for various purposes while working in SQL Server. Here I will give an example to convert a database table to a comma delimited string.
Behind The SceneBefore going to use the script that I will provide here you need to have some basic idea about the keyword STUFF ( Transaction SQL ).
The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
STUFF ( character_expression , start , length , replaceWith_expression )
Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.
Is an integer value that specifies the location to start deletion and insertion. If start or length is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned. start can be of type bigint.
Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. length can be of type bigint.
Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data. This expression will replace length characters of character_expression beginning at start.
Here use the query to convert the table to comma separated string value. Here the table used is 'YourtableName' replace it with the required table name, and the column name is 'Name'.
SELECT ComaDelimitedString = STUFF(( SELECT ',' + CAST(Name AS NVARCHAR(max)) FROM YourTableName FOR XML PATH ('') ),1,1,'')