尝试这个:
DECLARE @RowsLimit INT
,@columnsLimit INT;
SELECT @RowsLimit = 5
,@columnsLimit = 7;
DECLARE @DynammicTSQLStatement NVARCHAR(MAX)
,@DynamicPIVOTColumns NVARCHAR(MAX)
,@DynamicPIVOTResultsColumns NVARCHAR(MAX);
CREATE TABLE #Rows
(
[value] INT
);
CREATE TABLE #Colmuns
(
[RowID] INT
,[value] INT
);
INSERT INTO #Rows ([value])
SELECT TOP (@RowsLimit) + ROW_NUMBER() OVER(ORDER BY t1.[number])
FROM [master]..[spt_values] t1
CROSS JOIN [master]..[spt_values] t2
INSERT INTO #Colmuns ([RowID], [value])
SELECT TOP (@columnsLimit) ROW_NUMBER() OVER(ORDER BY t1.[number])
,ROW_NUMBER() OVER(ORDER BY t1.[number])
FROM [master]..[spt_values] t1
CROSS JOIN [master]..[spt_values] t2
SET @DynamicPIVOTResultsColumns = STUFF
(
(
SELECT ',REPLACE(''TAB-R#C' + CAST([value] AS VARCHAR(12)) + ''', ''#'', [value])'
FROM #Colmuns
GROUP BY [value]
FOR XML PATH('') ,TYPE
).value('.', 'NVARCHAR(MAX)')
,1
,1
,''
);
SET @DynamicPIVOTColumns = STUFF
(
(
SELECT ',[' + CAST([value] AS VARCHAR(12)) + ']'
FROM #Colmuns
GROUP BY [value]
FOR XML PATH('') ,TYPE
).value('.', 'NVARCHAR(MAX)')
,1
,1
,''
);
SET @DynammicTSQLStatement = N'
SELECT '+ @DynamicPIVOTResultsColumns +'
FROM #Rows
CROSS APPLY
(
SELECT *
FROM #Colmuns
PIVOT
(
MAX([value]) FOR [RowID] IN (' + @DynamicPIVOTColumns + ')
) PVT
) DS';
EXEC sp_executesql @DynammicTSQLStatement;
DROP TABLE #Rows;
DROP TABLE #Colmuns;