Dynamic Pivot

As another exercise, assume that you’re given the task of writing a stored procedure that produces a dynamic pivot in the database you are connected to. The stored procedure accepts the following parameters (all Unicode character strings): @query, @on_rows, @on_cols, @agg_func and @agg_col. Based on the inputs, you’re supposed to construct a PIVOT query string and execute it dynamically. Here’s the description of the input parameters:

  • @query. Query or table/view name given to the PIVOT operator as input

  • @on_rows. Column/expression list that will be used as the grouping columns

  • @on_cols. Column or expression to be pivoted; the distinct values from this column will become the target column names

  • @agg_func. Aggregate function (MIN, MAX, ...

Get Inside Microsoft® SQL Server™ 2005 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.