简体   繁体   中英

SQL - Can I rename a table name in a view?

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM