Dynamic PIVOT in SQL Server Without Hard-Coded Columns

A dynamic PIVOT is a PIVOT query whose column list is generated from the data at run time. Because PIVOT needs every output column named in its IN (...) list, you build the statement as a string and run it with sp_executesql. From SQL Server 2017, STRING_AGG and QUOTENAME make that string short and safe.
What PIVOT needs
The PIVOT documentation shows the shape: an aggregate, the column whose values become headers, and an IN list naming each header.
SELECT VendorID, [250], [251], [256], [257], [260]
FROM (
SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader
) AS src
PIVOT (
COUNT(PurchaseOrderID)
FOR EmployeeID IN ([250], [251], [256], [257], [260])
) AS pvt;The values in the IN list are identifiers, not parameters. If a new employee starts raising orders tomorrow, this query will not show them until someone edits it. The documentation also notes that a column appears for every value listed, even when it only holds NULL.
How a dynamic PIVOT works
The pattern has three steps: collect the distinct values, turn them into a delimited column list, and splice that list into the query text.
DECLARE @cols nvarchar(max), @sql nvarchar(max);
-- 1. Build "[250],[251],..." from the data
SELECT @cols = STRING_AGG(CAST(QUOTENAME(EmployeeID) AS nvarchar(max)), N',')
WITHIN GROUP (ORDER BY EmployeeID)
FROM (SELECT DISTINCT EmployeeID
FROM Purchasing.PurchaseOrderHeader) AS e;
-- 2. Splice the list into the statement
SET @sql = N'
SELECT VendorID, ' + @cols + N'
FROM (
SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader
) AS src
PIVOT (
COUNT(PurchaseOrderID)
FOR EmployeeID IN (' + @cols + N')
) AS pvt
ORDER BY VendorID;';
-- 3. Run it
EXEC sys.sp_executesql @sql;Each function has a specific job.
QUOTENAMEwraps each value in square brackets and escapes any]inside it, producing a valid delimited identifier. Its input is limited to 128 characters; longer values returnNULL.STRING_AGGjoins the names with a comma, andWITHIN GROUP (ORDER BY ...)fixes the column order. According to its reference page, the function exists from SQL Server 2017, returnsnvarchar(max)only when its input isnvarchar(max), and skipsNULLvalues. TheCASTtonvarchar(max)keeps a long list from hitting the 4,000-character limit of plainnvarchar.sp_executesqlruns the dynamically built statement and accepts parameters for any values in theWHEREclause.
Where it helps, and where it hurts
A dynamic PIVOT suits reports where the columns are data: months that keep growing, product codes, survey answers. It is a poor fit for application code that expects a fixed result shape. Every new value changes the column count, so the caller must read the metadata of each result set. The same problem appears when you try to select columns from the output of a stored procedure.
Security deserves the most care. Column names cannot be passed as parameters, so they have to be concatenated into the text. Microsoft's SQL injection guidance says never to concatenate user input that is not validated. Build the column list only from values read from your own tables, always through QUOTENAME, and pass filters such as dates as real parameters:
EXEC sys.sp_executesql @sql,
N'@from date, @to date',
@from = '2025-01-01', @to = '2025-12-31';That call assumes the WHERE clause inside @sql refers to @from and @to.
Two practical checks help when the output looks wrong. PRINT @sql (or SELECT @sql for long strings) shows the exact statement before it runs. If @cols is NULL because the source query found no rows, string concatenation makes @sql NULL as well, so test for that before calling sp_executesql.
On versions before SQL Server 2017, the usual way to build the list was FOR XML PATH('') with STUFF to remove the leading comma. The PATH mode documentation covers the XML side.
Conditional aggregation is the other route: SUM(CASE WHEN EmployeeID = 250 THEN 1 ELSE 0 END) AS [250] for each column. It needs the same dynamic string when the values are unknown, but it lets one query mix different aggregates per column, which PIVOT does not.
If the variable part is the sort order rather than the columns, dynamic SQL may not be needed at all: see dynamic ORDER BY without dynamic SQL.

More notes