Are you looking for
CREATE PROCEDURE MyProc
@FromDate DATE,
@ToDate DATE,
@Target SysName
AS
BEGIN
DECLARE @SQL NVARCHAR(MAX)= N'SELECT * FROM [' +
@Target +
'] WHERE [Dates] >= @FromDate AND [Dates] <= @ToDate';
EXECUTE sp_executesql @SQL,
N'@FromDate DATE, @ToDate DATE',
@FromDate,
@ToDate;
END
Demo
As I now understand what you are trying to do, you can
CREATE PROCEDURE ProcName
@FromDate DATE,
@ToDate DATE
AS
BEGIN
--Declare a variable to hold the Dynamic SQL
DECLARE @SQL NVARCHAR(MAX) = N'';
--Generate the databases names
WITH CTE AS
(
SELECT @FromDate D,
1 N
UNION ALL
SELECT DATEADD(Month, N, @FromDate),
N + 1
FROM CTE
WHERE N <= DATEDIFF(Month, @FromDate, @ToDate)
)
--Build the SELECT statement
SELECT @SQL = @SQL+
N'SELECT * FROM ['+
CONVERT(VARCHAR(3), D, 100)+
CAST(YEAR(D) AS VARCHAR(4))+
'].dbo.TableName UNION ALL ' --Or UNION as you want
FROM CTE;
--Remove the last UNION ALL
SET @SQL = LEFT(@SQL, LEN(@SQL) - 10); --If UNION then just -6
--Execute the statement
EXECUTE sp_executesql @SQL;
END
awith dates.