我是 SQL Server 的新手,我通过合并帖子创建了一个存储过程。
这是存储过程 - 除了它使用从第一个条目开始的天数并且随后不会更改它之外,它一切正常,因此我为每封电子邮件得到相同的@numberofdays。
ALTER PROCEDURE [dbo].[RenewalsCheck]
AS
DECLARE @CompanyName nvarchar (50) = NULL
DECLARE @ProductKey nvarchar (50) = NULL
DECLARE @ProductName nvarchar (50) = NULL
DECLARE @MaintenanceStartDate nvarchar (10) = NULL
DECLARE @MaintenanceEndDate nvarchar (10) = NULL
DECLARE @Result nvarchar (10) = NULL
DECLARE @Emailed int = NULL
DECLARE @Sent nvarchar (10) = NULL
DECLARE @Body nvarchar (max) = NULL
DECLARE @Subject nvarchar (max) = NULL
DECLARE @SalesManEmail nvarchar (max) = NULL
DECLARE @NumberOfDays nvarchar (5) = NULL
DECLARE @FollowUp int = NULL
DECLARE cEMail CURSOR LOCAL FAST_FORWARD FOR
Select
[CompanyName],
[Product Key],
[Product Name],
[Maintenance Start Date],
[Maintenance End Date],
[Emailed],
[SalesManEmail],
[FollowUp EC Emailed]
FROM dbo.Product
WHERE
datediff(d,GETDATE(),[Maintenance End Date]) < 15 AND [FollowUp EC Emailed] = '0'
SELECT
@NumberOfDays = datediff(d,GETDATE(),[Maintenance End Date])
FROM dbo.Product
WHERE datediff(d,GETDATE(),[Maintenance End Date]) < 15 AND [FollowUp EC Emailed] = '0'
OPEN cEmail;
WHILE 1 = 1
BEGIN
FETCH NEXT FROM cEmail INTO @CompanyName, @ProductKey, @ProductName, @MaintenanceStartDate ,@MaintenanceEndDate,
@Emailed, @SalesManEmail;
IF @@FETCH_STATUS = -1 BREAK;
SET @Body = 'The Product ' + @ProductName + ' with a product key of ' + @ProductKey + ' Expires in ' + @NumberOfDays + ' days.'
SET @Subject = 'Product Expiring in ' + @NumberOfDays + ' at ' + @CompanyName
EXECUTE msdb.dbo.sp_send_dbmail @profile_name='Jason',
@subject = @Subject,
@recipients = @SalesManEmail,
@copy_recipients ='',
@body = @body;
END
UPDATE [Product]
SET [FollowUp EC Emailed] = '1'
WHERE datediff(d,GETDATE(),[Maintenance End Date]) < 15 AND [FollowUp EC Emailed] = '0'
CLOSE cEmail;
DEALLOCATE cEmail;
我知道你们中的一些人会质疑它是如何设置的,并且可能有更好的方法来做到这一点,但我是新手,它除了一小部分之外还可以工作。
任何帮助是极大的赞赏。
问候
杰森