@Vasu ,
First, it would have been real nice of you to provide some readily consumable data instead of some nearly useless pictures. You're kind of new so I'm doing for you this time. Please do similar in the future to help us help you better and more quickly. Also, on forums that have no indication of version and edition, always be sure to include both.
Here's the code to provide the readily consumable data.
--===== Example Tables and data
DROP TABLE IF EXISTS #Table1,#Table2,#Table3
;
SELECT *
INTO #Table1
FROM (VALUES
( 1, 2, 4)
,(67,34,23)
)v(A,B,C)
;
SELECT *
INTO #Table2
FROM (VALUES
(11,22,14)
,( 6, 7,45)
)v(A,B,C)
;
SELECT *
INTO #Table3
FROM (VALUES
(99,98,97)
,(96,95,94)
)v(A,B,C)
;
Then do this... You can convert it stored procedure... you have t have some of the fun.
The code uses an iTVF (inline table valued function) that you can get from the "Resources" at the bottom of the following article.
https://www.sqlservercentral.com/articles/tally-oh-an-improved-sql-8k-%e2%80%9ccsv-splitter%e2%80%9d-function
--===== This is what would go into your stored procedure.
-- The first variable would be a parameter that you passed'
DECLARE @TableCSV VARCHAR(8000) = '#Table1,#Table2,#Table3'
;
--===== This would be a local variable in the stored procedure.
DECLARE @SQL VARCHAR(8000)
;
--===== This would check for and regject SQL Injection Attempts
-- If anything other than normal table name characters are detected,
-- eit silently so we don't give an attacker any hints.
IF @TableCSV LIKE '%[^-__ .,a-zA-Z0-9#[[]]]%'
BEGIN
PRINT 'wtf';
RETURN
END;
--===== Split the table names and create the dyamic SQL from those.
SELECT @SQL = ISNULL(@SQL+' UNION ALL'+CHAR(10),'')+' SELECT * FROM '+Item
FROM dbo.DelimitedSplit8K(@TableCSV,',')
;
--===== Print and execute the dynamic SQL. Comment out the PRINT if you want.
PRINT @SQL;
EXEC (@SQL)
;
And that creates the following output.
Try it with just one or two of the table names and you'll see that it works as expected.