This build in function introduced in the SQL server 2017
version. This works opposite the STRING_SPLIT function. With the help of this
function, we can concatenate the table rows value into the column.
Syntax of STRING_AGG
function
STRING_AGG(input_string, separator) WITHIN GROUP (ORDER BY column name)
|
Input_string is any type that can be
converted VARCHAR and NVARCHAR when concatenation.
The separator is the separator for the
result string. It can be literal or variable.
Order_clause specifies the sort order
of concatenated results using WITHIN GROUP clause
See the
example
With the
help String_AGG function we will achieve this very easily.
SELECT
Product_Category, Product_Sub_Category_Name,
STRING_AGG(Product_Name,',') Product_list
FROM
Project_Tran
GROUP BY
Product_Category, Product_Sub_Category_Name;
|
Before SQL
server 2017 for this scenario we need to write the user-defined function.