SQL 带游标的服务器存储过程

SQL Server Stored Procedure with cursor

我有以下存储过程,它基本上使用游标来获取今天有约会的人并向他们发送电子邮件。由于某种原因,此查询无法完成。当我尝试执行它时,它只是旋转,我不得不停止它。我让它 运行 一次长达 7 分钟,但我仍然没有收到错误或超时。不确定它在做什么。任何帮助将不胜感激。这是我的查询:

ALTER PROCEDURE [dbo].[spReminderEmail] 
AS
SET NOCOUNT ON;
DECLARE @MyCursor CURSOR
DECLARE @emailBody nvarchar(max)
DECLARE @subject nvarchar(max)
DECLARE @recipients nvarchar(max)
DECLARE @appointmentDate datetime
DECLARE @doctorFirstName nvarchar(max)
DECLARE @doctorLastName nvarchar(max)
DECLARE @groupName nvarchar(max)
DECLARE @location nvarchar(max)
DECLARE @count int

SET @count = 0

SET @MyCursor = CURSOR FAST_FORWARD For
Select StartTime, PersonEmail, DoctorFirstName, DoctorLastName, GroupName, Location  from vwAppointment where StartTime BETWEEN CAST(GETDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE)) AND IsActive = 1

Open @MyCursor
FETCH NEXT FROM @MyCursor INTO @appointmentDate, @recipients, @doctorFirstName, @doctorLastName, @groupName, @location

WHILE @@FETCH_STATUS = 0

BEGIN
    SET @emailBody = 'Hello from ' + @groupName + '. This is an email reminder of your appointment with ' + @doctorFirstName + ' ' + @doctorLastName + ' on ' + convert(varchar, @appointmentDate, 1) + ' at ' + @location + '.' + CHAR(13) + CHAR(10) + 'To help facilitate the meeting, please remember to bring with you any relevant documents (ID, insurance, etc.) and be prepared with questions for the office.' + CHAR(13) + CHAR(10) + 'If you are unable to make the appointment, please call ' + @groupName + ' or return to KSUAdvising and use the cancellation function. Cancellations are requested at least a day in advance.' + CHAR(13) + CHAR(10) + 'Late Policy:' + CHAR(13) + CHAR(10) + 'some text here...';
    SET @subject = 'REMINDER: Your Appointment with the ' + @groupName;
    SET @count = @count + 1     
END
CLOSE @MyCursor
DEALLOCATE @MyCursor

PRINT @count

if (@count > 0)
BEGIN
    EXEC msdb.dbo.sp_send_dbmail
    @profile_name='my_profile',
    @recipients=@recipients,
    @body=@emailBody, 
    @subject=@subject
END

在 WHILE 循环内(在 END 行之前)您必须添加:

FETCH NEXT FROM @MyCursor INTO @appointmentDate, @recipients,
  @doctorFirstName, @doctorLastName, @groupName, @location

为每个循环滚动查询记录

您永远不会获取下一行。所以你的循环将永远无所事事。您需要在 END 语句之前添加 FETCH NEXT FROM @MyCursor INTO @appointmentDate, @recipients, @doctorFirstName, @doctorLastName, @groupName, @location 。请参阅 This

底部的示例

您也可以尝试debug您的sp,以便将来在您的sp中找到问题的确切位置。