SQL STRING_AGG Function

The SQL Server STRING_AGG String Function concatenates the string expressions and places a specified separator in between them. Remember, it will not place a separator at the end of the string. The basic syntax of the SQL STRING_AGG function is

SELECT STRING_AGG (String_Expression, Separator)
FROM [Source]
GROUP BY Columns

The list of arguments available is

  • String_Expression: Please specify a valid Expression
  • Separator: Use VARCHAR or NVARCHAR type. This method will use this separator in-between string concatenation.
  • Group By: This is an optional argument. Use this to perform Grouping.

For this SQL Server demonstration, we are going to use the below-shown data.

Employee Table 1

SQL STRING_AGG Function Example

In this String example, we will concatenate the Last name column data using the STRING_AGG function.

SELECT STRING_AGG([LastName], ' , ') AS TextFile
  FROM [Employee]
STRING_AGG Example 2

In this example, we are going to implement the Grouping along with the String_Agg function.

SELECT STRING_AGG([LastName], ' , ') AS TextFile
  FROM [Employee]
  GROUP BY Occupation
SQL STRING_AGG Function 3