使用 CTE 在存储过程中获取不正确的语法错误

Getting incorrect Syntax Error In Stored Procedure with CTE

我正在尝试创建一个存储过程,我需要在其中找到给定经销商编号的所有最新条目,然后根据某些条件获取总数。我是这样创建的:

CREATE PROCEDURE [dbo].[GetNotificationCount] @DealerNumber varchar(50),
                                              @NotificationCount int OUT
AS
BEGIN
    DECLARE @UserId varchar(50);
    WITH Notifications (RequestId, StatusId, RequestStatusId, UserId, row_num) AS
        (SELECT r.ID,
                rs.StatusID,
                rs.ID,
                r.UserID,
                ROW_NUMBER() OVER (PARTITION BY r.Id, rs.StatusID ORDER BY DateTimeStamp DESC) AS row_num
         FROM Requests r
              INNER JOIN RequestStatuses rs ON r.ID = rs.RequestID
         WHERE r.DealerNumber = @DealerNumber)
    Set @UserId = (Select Top 1 UserId from Requests where DealerNumber = @DealerNumber)
    SELECT @NotificationCount = COUNT(*)
    FROM Notifications n
         INNER JOIN Statuses s ON n.StatusId = s.ID
    WHERE n.row_num = 1
      AND n.StatusId IN (SELECT ID FROM Statuses WHERE DealerPortal = 'Additional Info Needed')
      AND n.RequestStatusId NOT IN (SELECT RequestStatusId FROM AdditionalInfoViewed WHERE UserId = @UserId);
END;

但是我遇到了编译时错误

Incorrect Syntax near SET statement.

我不确定我哪里做错了。请提出建议。

在 cte 开始之前设置@UserId 值(在“with”关键字之前)

CREATE PROCEDURE [dbo].[GetNotificationCount]
@DealerNumber varchar(50),
@NotificationCount int out
AS
BEGIN
Declare @UserId varchar(50);
Set @UserId = (Select Top 1 UserId from Requests where DealerNumber = @DealerNumber)
;With Notifications (RequestId, StatusId, RequestStatusId, UserId, row_num)
AS
(
select r.ID, rs.StatusID, rs.ID, r.UserID, ROW_NUMBER() OVER (PARTITION BY r.Id,rs.StatusID ORDER BY DateTimeStamp DESC) as row_num
 from Requests r inner join RequestStatuses rs on r.ID = rs.RequestID
 where  r.DealerNumber = @DealerNumber

)
select @NotificationCount = Count(*) from Notifications n inner join  Statuses s
on n.StatusId = s.ID
Where n.row_num = 1 and n.StatusId in (Select ID from Statuses where DealerPortal = 
'Additional Info Needed') 
and n.RequestStatusId not in (select RequestStatusId from AdditionalInfoViewed where 
UserId = @UserId)
END

不允许在 CTE 中使用设置变量,您应该 SELECT 变量与 VIEW 的规则相同,或者填充 CTE 外部的变量

SELECT @UserId = .... 

应该可以

通用 table 表达式中变量的规则:MSDN