The SELECT statement below is from a stored procedure I am using to retrieve data which is subsequently sent to JSON:
SELECT *
FROM (
SELECT CAST(DateTimeUTC as SmallDateTime) as [DateTime], DataValue, VariableID
FROM DataValues
WHERE SiteID = @siteID and VariableID BETWEEN 9 and 10 and DateTimeUTC >= DATEADD (day, @pastDays, getdate())
) TableDate
PIVOT (SUM(DataValue) FOR VariableID IN ([9],[10])) PivotTable ORDER BY [DateTime]
What I would like to accomplish is to modify the procedure to accept a column range to pivot. In the above example I am only retrieving values for two variables. What if I want to retrieve VariableID 1 through 10, or 1 through 50? There has to be a way to retrieve 1 through 10 in a way other than:
VariableID IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10])
The Using PIVOT and UNPIVOT on MSDN doesn’t mention a way to specify a range.
I realize that it is possible to use dynamic SQL in a stored procedure, but given my own knowledge of SQL and the knowledge of those who will have to maintain this long term I am hesitant to introduce additional complexity by using dynamic SQL. There is a conceptually similar question on here, see TSQL Pivot Long List of Columns, and it was answered with a dynamic SQL solution.
Unfortunately, the
PIVOTfunction does not have the ability to generate the list of columns, without using dynamic sql.So your SQL code will be similar to this:
The key to this is the following code which generates the list of
variableIdsto become columns:This will create the list of all
distinctvariable id’s. This list is then added to the SQL query string to return.