-- 1. Fisrt of all, make a table like named "CommonDeviceLogs". (I assume you have an union query for old Device logs table).
-- 2. Then dump all the data from your current "DeviceLogs" tables into "CommonDeviceLogs" Table.
-- 3. Now in your SP make a Union Between "CommonDeviceLogs" table and
"DeviceLogs" table of current month i.e. like DeviceLogs_2_2024. like shown:
Demo : https://dbfiddle.uk/bjtZLnPW
DECLARE @TableName NVARCHAR(100);
SET @TableName = CONCAT('DeviceLogs_', MONTH(GETDATE()), '_', YEAR(GETDATE()));
DECLARE @SQLQuery NVARCHAR(MAX);
SET @SQLQuery = CONCAT('SELECT * FROM CommonDeviceLogs
UNION
SELECT * FROM ', @TableName);
EXEC sp_executesql @SQLQuery;
-- 4. And make a SQL job which will run on start of every month and dump the data of previous month in "CommonDeviceLogs" table. and Sp for this is:
CREATE PROCEDURE InsertPreviousMonthDataIntoCommonDeviceLogs
AS
BEGIN
DECLARE @PreviousMonth NVARCHAR(100);
SET @PreviousMonth = CONCAT('DeviceLogs_', MONTH(DATEADD(MONTH, -1, GETDATE())), '_', YEAR(DATEADD(MONTH, -1, GETDATE())));
DECLARE @SQLQuery NVARCHAR(MAX);
SET @SQLQuery = CONCAT('INSERT INTO CommonDeviceLogs SELECT * FROM ', @PreviousMonth);
EXEC sp_executesql @SQLQuery;
END
I think this approch is better than dynamically selecting all the tables like DeviceLogs_ names every time whenever the SP get called.