我创建了一个名为Customers
的表,其中包含以下列:
ID
Name
Birthdate
Email
Manager
条目
Name Birthdate Email Manager
---- ---------- -------------- -------
Jan 1986-05-15 jan@gmail.com None
Koos 1986-07-24 Koos@gmail.com 1
Sam 1991-07-24 Sam@gmail.com 1
意味着Koos和Sam的经理是Jan。
现在我想做的是确定某人今天是否过生日。
Create PROCEDURE [dbo].[EmailData]
AS
SET NOCOUNT ON
BEGIN
Declare @Date date
SELECT GETDATE(), Month(GetDate()), Day(GetDate()), Year(GetDate())
select
a.ID, a.Name,
a.BirthDate as EmpBirthday,
b.Name as Manager,
b.Email as ManEmail
from dbo.Customers a
inner join dbo.Customers b
on a.Manager = b.ID
where Month(a.BirthDate) = Month(GetDate())
and Day(a.BirthDate) = Day(GetDate())
END
Go
以上工作正常,我得到的结果我想100%。
我现在要做的是将今天生日的每位员工的电子邮件发送给员工的经理。
我想出了这个,但它似乎不起作用,我不明白为什么:
Create PROCEDURE EmailData
AS
BEGIN
Declare @email nvarchar(128)
Declare @Date date
SELECT GETDATE(), Month(GetDate()), Day(GetDate()), Year(GetDate())
DECLARE rcpt_cursor CURSOR FOR
select
b.Email
from dbo.Customers a
inner join dbo.Customers b
on a.Manager = b.ID
where Month(a.BirthDate) = Month(GetDate())
and Day(a.BirthDate) = Day(GetDate())
OPEN rcpt_cursor
FETCH NEXT FROM rcpt_cursor INTO @email
DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.gmail.com'
DECLARE @From nvarchar(128)
Set @From = 'My Email Address'
DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'Your Employees have a birthday today.'
DECLARE @User nvarchar(128)
Set @User = 'My Email Address'
DECLARE @Password nvarchar(128)
Set @Password = 'My Password'
DECLARE @SSL int
Set @SSL = 0
DECLARE @Port int
Set @Port = 587
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @email
DECLARE @subject nvarchar(255)
SELECT @Subject = 'Happy Birthday' + @email
EXEC EmailData @ServerAddr,
@from, @email, @subject, @BodyText, @User, @Password, @SSL, @Port
FETCH NEXT FROM rcpt_cursor
INTO @email
END
CLOSE rcpt_cursor
DEALLOCATE rcpt_cursor
End
Go
任何帮助将不胜感激。
答案 0 :(得分:0)
好的,我破解了它
首先,我设置了一个数据库邮件帐户
然后我写了一个程序
USE [Customers]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_SendEmail]
AS
Declare @email nvarchar(128)
Declare @name nvarchar(128)
Declare @Date date
SELECT GETDATE(), Month(GetDate()), Day(GetDate()), Year(GetDate())
DECLARE rcpt_cursor CURSOR FOR
select
a.Name,
b.Email
from dbo.Customers a
inner join dbo.Customers b
on a.Manager = b.ID
where Month(a.BirthDate) = Month(GetDate())
and Day(a.BirthDate) = Day(GetDate())
OPEN rcpt_cursor
FETCH NEXT FROM rcpt_cursor
INTO @name,@email
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @email
Declare @subject nvarchar(255)
Declare @Bodytext nvarchar(512)
Set @BodyText = @Name + '' + ' has a birthday today. Please congrad him'
Set @Subject = 'Employee Birthday'
exec msdb.dbo.sp_send_dbmail
@Profile_Name = 'HappyBirthday',
@Recipients = @email,
@Body = @BodyText,
@Subject = @Subject
FETCH NEXT FROM rcpt_cursor
INTO @name,@email
END
CLOSE rcpt_cursor
DEALLOCATE rcpt_cursor
Go
Exec [usp_SendEmail]
此过程现在通过孔客户表检查是否有生日日期,并将电子邮件发送给员工生日的经理。