如何避免SQL Server动态数据透视中的空间

时间:2014-01-08 03:25:01

标签: sql database sql-server-2008

我正在尝试在SQL Server 2008中进行动态透视,并收到以下错误。

错误消息

  

Msg 1038,Level 15,State 4,Line 2
  对象或列名称缺失或为空。对于SELECT INTO语句,请验证每列是否具有名称。对于其他语句,请查找空别名。不允许使用定义为“”或[]的别名。将别名更改为有效名称。

**笔记

  • #Temp_DOF2来自存储过程,具有相同的文件结构。

我的代码:

----------------------------------------------------------------------------- 
 --- Get a clean File structure before Pivoting --
------------------------------------------------------------------------------
Create Table #Temp_DOF
(
    Product_Family      Varchar(50) COLLATE Latin1_General_CS_AS ,
    Shipment_Date       Date  ,
    Part                Varchar(1000) COLLATE Latin1_General_CS_AS ,
    Order_No            Varchar(50) COLLATE Latin1_General_CS_AS ,
    [Group]         Varchar(50) COLLATE Latin1_General_CS_AS ,
    Outstanding_Qty         Int 

)

Insert Into #Temp_DOF

  SELECT 
        Product_Family,Shipment_Date,Part,Order_No,[Group],
        Outstanding_Qty

  From #Temp_DOF2
    ORDER BY Shipment_Date,Order_No,[Group]     

-------------------------------------------------------------------------                   
               -- Pivoting the Table. --
-------------------------------------------------------------------------  

--- Dynamic Pivoting.. Stuff the parameter with Part Valus and do the Pivoting.

DECLARE @Main_columns   AS NVARCHAR(MAX),
      @PVT_columns  AS NVARCHAR(MAX),
      @DOF_Results    AS NVARCHAR(MAX)


Set @Main_columns = STUFF((SELECT distinct ',' + QUOTENAME(Part) 
                    from #Temp_DOF 
                        FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') 

Set @PVT_columns = STUFF((SELECT Distinct ', isnull(' + QUOTENAME(Part) + ', 0) as ' + QUOTENAME(Part)
                     from #Temp_DOF
                        FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')  


Set @DOF_Results = 'Select Product_Family,Shipment_Date,Order_No, 
                     '+ @PVT_columns+ ', "Group"

                 FROM
                (
                  Select Product_Family,Shipment_Date,Order_No,"Group",
                          Part , Outstanding_Qty
                    From #Temp_DOF

             ) AS SrcTable

                 PIVOT

                (
                 SUM(Outstanding_Qty) FOR Part in (' + @Main_columns + ')
                ) AS PvTable  
                  Order By Shipment_Date,Order_No,"Group"'

Exec(@DOF_Results )

0 个答案:

没有答案