我有一个使用 CTE 的存储过程,但是要查询的表是可变的(我有几个具有相同结构的表),所以我尝试使用动态 SQL。 但它返回错误('set' 附近的语法不正确),因为我没有在查询中引用 CTE,因为动态 SQL 不计算在内(根据 CTE 后的语法不正确)
那我该如何解决呢?我有这个问题:
--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
非常感谢!