Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9242305
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T08:33:15+00:00 2026-06-18T08:33:15+00:00

The SELECT statement below is from a stored procedure I am using to retrieve

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T08:33:16+00:00Added an answer on June 18, 2026 at 8:33 am

    Unfortunately, the PIVOT function does not have the ability to generate the list of columns, without using dynamic sql.

    So your SQL code will be similar to this:

    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)
    
    select @cols = STUFF((SELECT distinct ',' + QUOTENAME(VariableID) 
                        from DataValues
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    set @query = 'SELECT [DateTime], ' + @cols + ' from 
                 (
                    SELECT CAST(DateTimeUTC as SmallDateTime) as [DateTime], 
                        DataValue, 
                        VariableID
                    FROM DataValues
                    WHERE SiteID = '+cast(@siteID as varchar(10))+'
                        -- and VariableID BETWEEN 9 and 10 -- remove the variableID filter
                        and DateTimeUTC >= DATEADD (day, +'cast(@pastDays as varchar(10))+', getdate())
                ) x
                pivot 
                (
                    SUM(DataValue)
                    for VariableID in (' + @cols + ')
                ) p '
    
    execute(@query)
    

    The key to this is the following code which generates the list of variableIds to become columns:

    select @cols = STUFF((SELECT distinct ',' + QUOTENAME(VariableID) 
                        from DataValues
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    

    This will create the list of all distinct variable id’s. This list is then added to the SQL query string to return.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a procedure which has a select statement as below: CREATE PROCEDURE pr_test
I am writing a stored procedure using MySql which returns multiple rows using select
Using a stored procedure i have a fairly complex SQL statement which returns a
I m creating stored procedure with multiple select statement,as shows below: DELIMITER $$ DROP
The following statement is in a Stored Procedure MERGE INTO table1 a USING (SELECT
I want to write an SQL statement like below: select * from tbl where
I'm trying to do the below sql statement in GORM select * from table1
I have created a procedure and used the below statement inside that . select
I have a select statement running which pulls data into $row. $result = mysql_query(Select
I have a SELECT statement like this: SELECT T1.COD, T1.NAME, (SELECT MAX(T2.DATA) FROM dbo.TAB2

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.