Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Pivot dinamico di SQL Server 2005

Ho fatto troppe di queste query dinamiche negli ultimi tempi... (le mie colonne cambiano in base al cliente di mese in mese). Ecco un modo per farlo:niente test, niente debug, potrebbero esserci alcuni bug da appianare:

DECLARE
  @Command     nvarchar(max)
 ,@ColumnList  nvarchar(max)
 ,@OrderId     int
 ,@Debug       bit


--  Build a comman-delimited list of the columns
SELECT @ColumnList = isnull(@ColumnLIst + ',', , '') + ColName
 from dbo.GetTableColumnNames('OrderCash', 2)


--  Insert the list of columns in two places in your query
SET @Command = replace('
SELECT  OrderID, 
        CurrCode + ‘‘GBP CURNCY’‘ AS Ticker, 
        Cash AS Position 
FROM 
( 
    SELECT OrderID, <@ColumnList>
    FROM OrderCash 
) p 
UNPIVOT 
( 
    Cash FOR CurrCode IN  
    (<@ColumnList>) 
) AS unpvt 
WHERE Cash != 0 
And OrderID = @OrderId
', '<@ColumnList>', @ColumnList)


--  Always include something like this!
IF @Debug = 1
    PRINT @Command

--  Using sp_executeSQL over EXECUTE (@Command) allows you execution
--  plan resuse with parameter passing (this is the part you may need
--  to debug on a bit, but it will work)
EXECUTE sp_executeSQL @Command, N'@OrderId int', @OrderId