Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin.
Search for scripts directly from SSMS, and instantly access any saved scripts in your
SSC briefcase from the favorites tab.
Download now (direct download link)
Thank this author by sharing:
This is a stored procedure to transponse N rows from a specified table.
I have found copying a transposed table to Excel useful for reviewing data from a table with many columns. A transposed table derived from a limited number of rows will not exceed Excel's maximum number of columns, and the transposed data is often easier to navigate and read.
Other transpose procedures I have found on the web are somewhat limited: they assume the columns in the original table are of the same numeric data type. This procedure handles tables with columns of varying data types; the workaround is to cast all data in the output table as varchar(max).
Also, please note that this procedure does NOT return a crosstab table. Crosstabs return summary data (totals or counts), not the original data. In certain specific circumstances (when the cases in a base table are unique) a crosstab procedure can return a transpose of the original data. Again, however, this use is limited to numeric data.
A portion of the procedure was adapted from MSDN community content. Thanks to the original posting member (Brindha Raji) and additional revising members. Please see the procedure code for the reference URL.
SYNTAX:EXEC usp_TransposeNRows @TableName [, @NRows]
PARAMETERS: @TableName - Name of table to be transposed (REQUIRED)@NRows - Number of rows to transpose (OPTIONAL; Default = 0, max = 1022)
(When @NRows = 0, the procedure returns a table containing just the column order and column names)
Transposing rows into columns
script to return query result transposed.
Transpose rows to columns.
SQL Transpose Data
Procedure return value problem