Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Server 2016 String Aggregate Functions Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

SQL Server 2016 does not include a built-in STRING_AGG function—that arrived in SQL Server 2017. To concatenate rows into a single string in SQL Server 2016, you use the XML PATH method or a CLR aggregate. This guide shows you the practical, working approach for 2016, including the exact syntax, common pitfalls, and how to handle NULLs, ordering, and performance.

What You'll Need

  • SQL Server 2016 (any edition) with a database you can query.
  • A SQL client such as SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Basic familiarity with SELECT, FROM, and GROUP BY.
  • Permission to run SELECT queries and, if you use the CLR option, permission to enable CLR integration (usually a DBA task).

Step-by-Step

  1. Understand the goal. You want to turn multiple rows into one delimited string per group—for example, a list of product names per category. In SQL Server 2016 you cannot use STRING_AGG; you will use FOR XML PATH or a CLR aggregate.
  2. Start with the XML PATH pattern. The most common 2016 technique uses a correlated subquery with FOR XML PATH. The basic shape is:
    SELECT CategoryID,
    STUFF((SELECT ', ' + ProductName
    FROM Products p2
    WHERE p2.CategoryID = p1.CategoryID
    FOR XML PATH('')), 1, 2, '') AS ProductList
    FROM Products p1
    GROUP BY CategoryID;
  3. Explain the parts. FOR XML PATH('') produces an XML fragment with no root element, effectively concatenating the values. STUFF removes the leading delimiter (the first two characters in the example). The correlated subquery ties each row to its group.
  4. Handle special characters. If your data contains &, <, or >, XML PATH will escape them as &amp;, &lt;, and &gt;. To avoid escaping, use FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') instead of the plain PATH. Example:
    STUFF((SELECT ', ' + ProductName
    FROM Products p2
    WHERE p2.CategoryID = p1.CategoryID
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
  5. Control the order. Add an ORDER BY inside the subquery to sort the concatenated values:
    SELECT ', ' + ProductName
    FROM Products p2
    WHERE p2.CategoryID = p1.CategoryID
    ORDER BY ProductName
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
  6. Exclude NULLs. Concatenation with NULL yields NULL in the output for that row, which can leave stray delimiters. Filter them out with WHERE ProductName IS NOT NULL inside the subquery.
  7. Test with a small dataset. Run your query against a few rows first. Compare the output to what you expect. Check for leading/trailing delimiters and correct grouping.
  8. Consider the CLR aggregate alternative. If you need better performance on large datasets, you can deploy a custom CLR aggregate (often called a “string concatenate” aggregate). This requires enabling CLR integration (sp_configure 'clr enabled', 1; RECONFIGURE;) and deploying a signed assembly. This is an advanced option and usually requires DBA involvement.
  9. Wrap it in a view or stored procedure. Once the query works, save it as a view for reuse. For parameterized reports, use a stored procedure.

Common Mistakes

  • Forgetting STUFF. Without STUFF, the result starts with your delimiter (e.g., “, Apple, Banana”). Always trim the leading delimiter.
  • Using FOR XML PATH without TYPE. This causes XML escaping of special characters. Use the TYPE and .value() pattern when your data may contain &, <, or >.
  • Ignoring NULLs. NULL values can break concatenation or leave empty slots. Filter them explicitly.
  • Assuming STRING_AGG works. It does not exist in SQL Server 2016; scripts copied from newer versions will fail with “Invalid object name 'STRING_AGG'”.
  • Poor performance on large tables. The correlated subquery runs per group. For large datasets, test performance and consider indexing the grouping and ordering columns.

Tips

  • Use NVARCHAR(MAX) in the .value() call to avoid truncation on long strings.
  • Keep delimiters consistent; a comma plus space is common but pick one and stick to it.
  • If you need to concatenate across multiple columns, build the string inside the subquery with + and handle NULLs with ISNULL or COALESCE.
  • For distinct values, add DISTINCT inside the subquery, but be aware it can affect ordering.
  • Document the XML PATH pattern in your codebase—new team members may expect STRING_AGG.

Troubleshooting

If your query returns an error about XML or invalid characters, switch to the TYPE/.value() pattern. If the output has extra delimiters, check for NULLs or empty strings in the source column. If performance is slow, examine the execution plan; the correlated subquery may benefit from an index on the grouping column and the column being concatenated. If you see escaped characters like &amp;, you are using FOR XML PATH without TYPE—apply the fix above. If you cannot enable CLR for the aggregate alternative, stick with XML PATH; it works in all editions.

Frequently Asked Questions

Does SQL Server 2016 have STRING_AGG?

No. STRING_AGG was introduced in SQL Server 2017. In 2016, use FOR XML PATH or a CLR aggregate.

Can I use STRING_AGG in compatibility level 130?

No. The function is not available in any compatibility level on SQL Server 2016; it is a version-level feature.

What is the STUFF function doing in the XML PATH pattern?

STUFF removes the first delimiter from the concatenated string. For example, STUFF(', A, B', 1, 2, '') returns 'A, B'.

How do I avoid XML escaping in FOR XML PATH?

Use FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') instead of plain FOR XML PATH(''). This returns unescaped text.

Can I order the concatenated values?

Yes. Add an ORDER BY clause inside the subquery before the FOR XML PATH clause.

Is there a performance difference between XML PATH and CLR?

CLR aggregates can be faster on large datasets, but they require enabling CLR integration and deploying an assembly. XML PATH is simpler and works everywhere, but may be slower on very large tables.