This question is the follow-up of this thread
Given that I've created two simple tables User and Item:
- User (Id, Name, Email)
 - Item (Id, CreatedDate, EmailSent, UserId)
 
I am able to create an SQL Server Agent job that periodically runs the following script:
USE test
DECLARE @emails varchar(1000)
SET @emails = STUFF((SELECT ';' + u.Email FROM [user] u JOIN [item] i 
ON u.ID = i.UserId 
WHERE i.EmailSent = 0 AND DATEDIFF(day, i.CreatedDate, GETDATE()) >= 30 
FOR XML PATH('')),1,1,'')
/** send emails **/
EXEC msdb.dbo.sp_send_dbmail 
@profile_name='test',
@recipients=@emails,
@subject='Test message',
@body='This is the body of the test message.'
The purpose is to get any item that has been created for >= 30 days and then send a reminder email to its user. The EmailSent is checked first to exclude items already reminded.
I want to improve this script as follows:
- There's a separate query that does the 
SELECTpart and stores the result into a variable so that it can be reused in the email sending query, and in anUPDATEquery that sets selected items'EmailSenttoTrue(done after emails sent). - Customise the title and body of the message with user's 
Nameand item'sId. Something like: DearName, the itemIdhas been created for 30 days or more. 
Anybody has any idea of how these improvement could be done?