Question

I have what I thought was a simple question but havent been able to resolve it in months , so here it goes !!!

Environment : Microsoft SQL 2008

I have a qyery that runs every night and gives me a list of all orders that dont have an approval code:

Query :

Select OrderId, First , Last ,Email from Orders where Approval is Null

Results:

OrderID First Last Email

4565 Tom Cruise Tom@email.com

3423 Jaime Fox jaime@email.com

Thats fine becuase now i know which orders dont have an approval but what i want to do is for the query to atomatcally email them something like

Desired Result Dear Tom ,

Your order does not have an approval code and will be cancelled within the next 48 Hours if the code is not entered.

* Desired Result**

At any given time i may have 30 of these orderd so the query needs to just run and generate an email to each person . if 1 person has multiple orders it is fine if they get an email for each order seperatly . Please Help!! and by help I mean please let me see sample code to how to achieve this since i dont know how to. Thank You

Was it helpful?

Solution

You can use the email capabilities in SQL Server for sending the emails.

Once you configure SQL Server (follow this link); you can simply go through each email in a loop, like so:

USE msdb
GO
EXEC sp_send_dbmail @profile_name='PinalProfile',
@recipients='tomcruise@Example.com',
@subject='Your Order',
@body='Hi there.'

Update

Here's an example of how to iterate through the records:

declare @temp as table
(
Id int identity,
OrderId int, 
First varchar(255), 
Last varchar(255),
Email varchar(512)

)

insert into @temp
Select OrderId, First , Last ,Email from Orders where Approval is Null

declare @email varchar(512)
       , @index int=1 
       , @upper_bound int
       , @subject varchar(500)

select @upper_bound=max(Id) from @temp


while(@index<=@upper_bound)
BEGIN
select @email=email,@subject='Your order number '+OrderID from @temp where Id=@index

EXEC msdb.dbo.sp_send_dbmail @profile_name='profile',
@recipients=N@email,
@subject=@subject,
@body='Whatever you want to say here.'

select @index=@index+1

END

-- You are done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top