【发布时间】:2015-07-03 04:13:32
【问题描述】:
我有以下存储过程,它基本上使用光标来获取今天有约会的人并向他们发送电子邮件。由于某种原因,此查询将无法完成。当我尝试执行它时,它只是旋转,我不得不停止它。我让它运行一次长达 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 循环中使用 FETCH NEXT。
-
如果工作正常但突然停止工作,则可能是统计问题或存储过程需要重新编译。
标签: sql-server stored-procedures scheduled-tasks