Dynamic Pivot (in SQL Server 2005)

被刻印的时光 ゝ 提交于 2019-12-13 02:05:27

问题


I'm writing a stored procedure for Microsoft SQL 2005 and I want to create a dynamic SQL Pivot:

SELECT Book.ISBN,
       Book.Name
       StockMutation.StockLocation
FROM   Book INNER JOIN StockMutation AS sm ON Book.bookid = sm.bookid
PIVOT
(
       COUNT(sm.NumberOfBooks)
       FOR sm.StockLocation IN (...)
)

Preferable I want to replace (...) with:

SELECT StockLocation.StockLocation FROM StockLocation

and not hardcode all locations in the procedure ([Location1],[Location2],etc.), but SQL doesn't accept this.

How do I solve this?


回答1:


You can't do it in pure SQL, you have to use dynamic SQL and build the actual SQL you want to execute.

You can do this like so:

DECLARE @sql VARCHAR(8000)
SET @sql = 'FOR sm.StockLocation IN ('

DECLARE cursor...

LOOP cursor...

SET @sql = @sql + '''' + column_name + ''','

// end loop

EXEC(@sql)


来源:https://stackoverflow.com/questions/1827256/dynamic-pivot-in-sql-server-2005

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!