Search code examples
sqlsql-servertemp-tables

How can I create a new temp table for each day given in a range?


I need to create a temp table based on days given in example,

I need temp tables for 2015-06-08 to 2015-06-29, I am going to create 22 temp tables, each having their own data according to date.

My query would select data into these temp tables in a loop and the only thing that needs to change is the date.


Solution

  • As everyone here is suggesting you that you do not need a table for each date but a row in a table for each date, Also you don't necessarily need to store the results into a temp table.

    You can write a query which produces this date range and join your existing query with the result of date range query.

    Storing results of a query is good for humans to visually see the data but sql server doesn't need data in a temp table to proceed with data processing, if you have a query which you know will produce a specific result set, you can join another table with that result set, you don't see the result set at runtime but sql server gets that result set at runtime and joins it with your table.

    Now hopefully if I have convinced you that you do not need a temp table for each date lets talk about the solution.

    All you need is a query which produces a result set with dates ranging 2015-06-08 to 2015-06-29 for this you can do the following:

    DECLARE @From DATE = '2015-06-08' 
    DECLARE @To   DATE = '2015-06-29'
    
    SELECT Dates 
    FROM 
      (
        SELECT TOP  (DATEDIFF(DAY,@From , @To))
          DATEADD(DAY , 
                      ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
                    ,@To) AS Dates
       FROM master..spt_values
      )Dates_Table
    

    The above query will produce a result set with dates, now you can join another table with this result set to get the final result you need.