I have a stored procedure that uses a CTE, however the table to be consulted is variable (I have several tables with the same structure), so I try use dynamic SQL.
But it returns an error ("incorrect syntax near 'set'"), because I'm not referencing the CTE in query because dynamic SQL doesn't count (according Incorrect syntax after CTE)
So how do I resolve this? I have this query:
--Dynamic SQL
DECLARE @sql nvarchar(max)
--Extract hour value
DECLARE @hourDate DATETIME = DATEADD(hour,DATEDIFF(hour,0,@beginDate),0);
DECLARE @minutes INT = DATEPART(minute,@beginDate);
DECLARE @outmin INT;
DECLARE @startDate DATETIME;
DECLARE @interval INT=15;
--Verify Next Minute
IF @minutes <= 14
SET @outmin = 14;
ELSE IF @minutes > 14 AND @minutes <=29
SET @outmin = 29;
ELSE IF @minutes > 29 AND @minutes <= 44
SET @outmin = 44;
ELSE IF @minutes > 44 AND @minutes <=59
SET @outmin = 59;
--Add Minute
SET @startDate = DATEADD(minute,@outmin,@hourDate);
;WITH Dates(Date) AS
(
SELECT DATEADD(MINUTE, @interval, @StartDate) AS Date
UNION ALL
SELECT DATEADD(MINUTE, @interval, Date) AS Date
FROM Dates
WHERE Date < @endDate
)
set @sql='SELECT a.Date
FROM Dates a
left join '+ @tableName +' b on a.Date=b.TimeStampFrame
where b.TimeStampFrame is null
ORDER BY a.Date ASC
option (maxrecursion 0)'
exec sp_executesql @sql
Thanks a lot!