I have tables named:
Posts_August_2011
Posts_September_2011
Posts_October_2011
Posts_November_2011
Posts_December_2011
Posts_January_2012
I want to create stored procedure that would UNION tables,but that is not the problem since I can use dynamic SQL to glue it up, my problem is getting Months and Year Range from RANGE to some kind of list? and then checking if table exist, Union them and return.
I would declare 2 variables @FromDate and @Todate as datetime
What would be the best way to extract month name and year for each of the months in given range.
Say I give it a range @FromDate = '2011-10-18 14:16:27.000' and can someone advise how to extract Month and year.
@ToDate = '2012-01-09 14:16:27.000'
DECLARE @SqlToExecute as nvarchar(MAX);
using dinamyc SQL is acceptable,It could check for existence of table in while loop and
glue to string for each table that exists in range as:
@SqlToExecute += 'SELECT * FROM Posts_' + extractedMonthName + '_' + extractedYear + ' UNION ALL ';
This problem is caused by bad database design. You needed to store rows from all this tables in one table
Postswithdatefield to specify Month and Year.To get names of tables
Posts_%and date extracted from their names you can use following code:sys. tables is system catalog view which returns a row for each table object in the current database.