SQL SERVER 2012
DECLARE @TABLE TABLE
(
BASENAME varchar(150),
DESCRIPTIONS varchar(150)
)
insert @TABLE
SELECT 'Accessory', 'Color' UNION ALL
SELECT 'Accessory', 'Compatibility'UNION ALL
SELECT 'Accessory', 'Finish'UNION ALL
SELECT 'Accessory', 'Material'UNION ALL
SELECT 'Accessory', 'Mount Type'UNION ALL
SELECT 'Adapter', 'Adjustable'UNION ALL
SELECT 'Adapter', 'Ampere'UNION ALL
SELECT 'Adapter', 'Compatibility'UNION ALL
SELECT 'Adapter', 'MountType'UNION ALL
SELECT 'Adapter', 'Operation Type'UNION ALL
SELECT 'Adapter', 'Vertical Lift'UNION ALL
SELECT 'Adapter', 'Drawbar'UNION ALL
SELECT 'Adapter', 'Switch'
输出
BASENAME DESC1 DESC2 DESC3 DESC4 DESC5 DESC6 DESC7 DESC8
Accessory Color Compatibility Material Mount Type NULL NULL NULL NULL
Adapter Adjustable Ampere Compatibility MountType Operation Type Vertical Lift Drawbar Switch
其中一个BASENAME的DESC最大数量为DESC 50。 STUFF在这种情况下不起作用,因为它正在创建错误
错误:选择列表中的元素数量超过了允许的最大数量4096个元素。
我试过的代码:
DECLARE @Cols NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
DECLARE @Sel NVARCHAR(MAX);
DECLARE @GENERIC NVARCHAR(MAX)
SET @Cols = STUFF((SELECT distinct ',' + QUOTENAME([Description])
FROM STAGING_TEMP
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
SET @Sel = STUFF((SELECT distinct ',' + QUOTENAME([Description]) +
' AS DESC'+CAST(row_number () over (partition by [Generic Name] order by [description]) as varchar(250))
FROM STAGING_TEMP
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
SET @SQL = N'
SELECT DISTINCT [Generic Name], '+ @Sel+N'
FROM STAGING_TEMP
pivot
(
MAX(Description) For Description IN ('+ @Cols + N')
) P';
EXECUTE( @SQL);
是否有其他方法可以实现所需的输出。
答案 0 :(得分:0)
虽然您没有提供STUFF()
代码段,但听起来您正在以defined in the documentation达到SQL Server SELECT / INSERT语句的限制。
Columns per SELECT statement 4,096
Columns per INSERT statement 4,096
另请注意,每个非全局表的列数为1,024。