Reputation: 27
Can I rename a table name in a view? I have a view which I need to update the table name automatically each monthly. For example;
SELECT *
FROM Feb_Data
Change to
SELECT *
FROM Mar_Data
I have tried different ways via dynamic SQL and it doesn't work and I need a view because the data is too large. I have tried SP_RENAME
(This only works on columns or the view name).
Or can anyone else think of a better way to automate this?
Upvotes: 1
Views: 1129
Reputation: 152556
Well the best solution is to reorganize your database into one table instead of tables per month (possibly using views to mimic the old monthly table structure), but if that is not an option...
One option without Dynamic SQL is to select all tables in a UNION and filter by the current date
SELECT *
FROM Jan_Data
WHERE MONTH(GETDATE()) = 1
UNION ALL
SELECT *
FROM Feb_Data
WHERE MONTH(GETDATE()) = 2
...
(I make no promises about performance; this is purely for ease of maintenance, but the optimizer may take care of any performance concerns)
As a side note, what happens at the end of the year? Does Jan_Data get replaced? Having separate tables just by month (not by year) would seem to be quite limiting.
Upvotes: 1
Reputation: 8101
One way may be to write a stored procedure with a dynamic ALTER VIEW
statement in it which sets the table name according to the needed month name. Then set up a job to run the procedure at midnight on the first of the month.
Something along these lines (pretty much just pseudo code):
CREATE PROCEDURE dbo.AlterViewWithMonthlyTableNames
AS
BEGIN
DECLARE @TableName SYSNAME = CONCAT(CAST(GETDATE() AS NCHAR(3)),'_Data')
,@SQL NVARCHAR(1000);
SET @SQL = CONCAT
(
'ALTER VIEW dbo.YourView
AS
SELECT *
FROM ', QUOTENAME(@TableName),';'
);
EXEC sp_executesql @SQL;
END
Upvotes: 0