Hi,I've been thinking about this for a while and I can't seem to come up with a viable solution. I have a situation where some tables are named with years (e.g., Sales_2010, Sales_2011, Sales_2012, etc.) I would like to union in a view so that I'm working with a better structure (Id, Year, column1, column2, column3)[code]SELECT Id, 2010, column1, column2, column3FROM Sales_2010UNION ALLSELECT Id, 2011, column1, column2, column3FROM Sales_2011UNION ALLSELECT Id, 2012, column1, column2, column3FROM Sales_2012[/code]Problem 1: I can't use dynamic SQL inside of a view, so that complicates things. But OK, let's say that I just build out the next 100 years and UNION ALL future years:[code]SELECT Id, 2010, column1, column2, column3FROM Sales_2010UNION ALLSELECT Id, 2011, column1, column2, column3FROM Sales_2011UNION ALLSELECT Id, 2012, column1, column2, column3FROM Sales_2012UNION ALLSELECT Id, 2013, column1, column2, column3FROM Sales_2013UNION ALLSELECT Id, 2014, column1, column2, column3FROM Sales_2014UNION ALLSELECT Id, 2015, column1, column2, column3FROM Sales_2015UNION ALLSELECT Id, 2016, column1, column2, column3FROM Sales_2016UNION ALLSELECT Id, 2017, column1, column2, column3FROM Sales_2017UNION ALLSELECT Id, 2018, column1, column2, column3FROM Sales_2018...[/code]Problem 2: SQL Server (rightfully) gives me the error "Invalid object name 'Sales_2018'."Can anyone think of a way to accomplish this using only a view? Is there a way to trick SQL Server into ignoring the tables that don't yet exist?Thanks,MikeEdit: Added Problem 2
↧