I'm trying to send an email using the sql server email option, I already can send an email, but now I'm trying to send that email to dynamic recipients, for example... I have the following table:
ID | Email
..1| example#example.com
..2| example2#example.com
With my code I need to do the following thing:
#recipients = 'example#example.com; example2#example.com;'
What I want to do is to select that emails from a table, so if I edit one email I dont have to change anything about my code, just update the information from my table.
I'm thinking maybe do it by using a var, something like:
Declare #emails nvarchar(max)
set #email = query
then do something like a foreach (foreach email in #emails) or something like that (in T-SQL of course...)
Is this possible? Or what another solution can I try?
Recipients has the option to add more than one email in the same line, so maybe the easier way to solve your problem is select all the emails and then join them separated with a ;. If you thing that this is a good option you should try this code:
Declare #Emails nvarchar(MAX)
Select #Emails = coalesce(#Emails + ';', '') + Email from yourTable
//Your output should be: example#example.com;example2#example.com
Then all you need to do this:
#recipients = #Emails
You should use a cursor for that
DECLARE #email nvarchar(max)
set #email = ''
DECLARE #cursorName CURSOR FOR
SELECT emailColumn FROM tableName
OPEN #cursorName
Then you use a loop to concatenate each email
FETCH NEXT FROM #cursorName INTO #email
WHILE ##FETCH_STATUS = 0
BEGIN
set #email = #email+#cursorName+'; '
END
You need to concatenate the strings in the column, so something like this should work:
CREATE TABLE dbo.exampleTable (
id int,
email varchar(200)
)
INSERT INTO dbo.exampleTable VALUES (1,'a#a'),(2,'b#b')
SELECT stuff( (SELECT ';'+email
FROM dbo.exampleTable
FOR XML PATH(''), TYPE).value('.', 'varchar(max)')
,1,1,'')
There are also some other ways to do it: https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
The result of the query you build or use can be used to set your #email variable.
Related
I am getting the following error while trying to create a trigger on a table which sends an email to me:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
Basically what I have done is:
set #stu = (select name, year, gender from studentinformation where id = #id)
set #bod = ' Details changed for ' + #stu
Exec msdb.dbo.sp_send_dbmail #body = #bod;
I have just shown that part of code which I think would be having issue. I feel putting brackets is making SQL feel it's a subquery? Is that the reason? But then how do I send results of a query through a trigger via email? The select statement refers to another table not the one on which the trigger is based
you should specify your query in the #query parameter of sp_send_dbmail
exec sp_send_dbmail
#query = 'select name,year,gender from studentinformation where id = 1234',
... -- some other parameters
please refer to the documentation on sp_send_dbmail for further details
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-send-dbmail-transact-sql?view=sql-server-2017
You can only have 1 value in #stu. You're trying to populate it with name, year and gender.
I suggest DECLARE for your other values, so somethign like
DECLARE #stu varchar(100)
DECLARE #MyYear INT
DECLARE #MyGender varchar(10)
set #stu = (select name from studentinformation where id=#id)
set #MyYear = (select Year from studentinformation where id = #id)
set #MyGender = (select gender from studentinformation where id = #id)
I want to select name in email
Example:
sample#gmail.com
From that, I want to select 'sample' only.
This is for MS SQL Server. You can easily replicate this if you use any other RDBMS
declare #email varchar(100)
set #email='sample#gmail.com'
select substring(#email,1,charindex('#',#email)-1)
Try this
declare #email nvarchar(200) = 'sample#gmail.com'
select left(#email,charindex('#',#email,0)-1)
Like the title says, I'm trying to make a stored procedure used to send emails to addresses stored in the database, often including multiple recipients. I've tried a few approaches to this, but I think I'm hitting a wall and would appreciate any input anyone has. The main issue I've had is querying the database for the addresses and passing that to sp_send_dbmail in a way that works.
The address table is pretty simple, looks something like this, but much larger. Both columns are varchars:
idNumber | email
__________________________
a123 | steve#test.com
a123 | carol#test.com
1-100 | mary#test.com
So if we're sending to ID number "a123", an email needs to go to both Steve and Carol.
Here's a super simple procedure. It's not verbatim since this is all on my work computer, but more of a skeletal gist of what I'm going after.
CREATE PROCEDURE sendMail
#idNumber varchar(MAX),
#subject varchar(MAX),
#body varchar(MAX)
EXEC msdb.dbo.sp_send_dbmail
#recipients = "EXEC SELECT email FROM emailTable WHERE idNumber = " + #idNumber + "';",
#subject = #subject,
#body = #body;
It throws and error; it doesn't seem to like concatenating the ID parameter into the query. I tried making a separate procedure to query emails, but passing the ID parameter to the procedure didn't seem to work either. Even if I did successfully pass the parameter and get the query to execute successfully, I'd still need to join the two results in a single string and delimit them with semicolons so they'll play nice with sp_send_dbmail. I think?
SQL wizards, how would you approach this? I'm not wildly experienced, so is there something simple and syntactic I'm doing wrong? Is my approach flawed fundamentally?
I appreciate your input. Thank you.
EDIT: Here's Kritner's working solution! Thanks a bunch!
CREATE PROCEDURE testMail2
#idNumber varchar(MAX)
AS
BEGIN
DECLARE #recipientList varchar(MAX)
SET #recipientList = (STUFF((SELECT ';' + email FROM emailTable WHERE idNumber = #idNumber FOR XML PATH(' ')),1,1,''))
EXEC msdb..sp_send_dbmail
#recipients=#recipientList,
#subject='Subject Line',
#body='Body Text'
END
You can do a query and assign the values to a variable as such:
DECLARE #myRecipientList varchar(max)
SET #myRecipientList = (STUFF((SELECT ';' + emailaddress FROM table FOR XML PATH('')),1,1,''))
This will set your #myRecipientLIst to a ";" delimited list of the recipients specified your query.
You could also do the same sort of idea with a SP, just throw them into a temp/variable table and stuff into a semi colon separated list.
EDIT:
Finally to send the mail you could do:
EXEC msdb.dbo.sp_send_dbmail
#recipients = #recipientList,
#subject = #subject,
#body = #body // ........
COMMENT EDIT:
based on your original query, your stuff query should look something like this:
DECLARE #myRecipientList varchar(max)
SET #myRecipientList = STUFF((SELECT ';' + email FROM emailTable WHERE idNumber = #idNumber FOR XML PATH('')),1,1,'')
The idea behind this is - for every email found in the email table append to #myrecipientList the email found and a semi colon.
I have strings in a database like this:
firstname.lastname#email.com/IMCLientName
And I only need the characters that appear before the # symbol.
I am trying to find a simple way to do this in SQL.
DECLARE #email VARCHAR(100)
SET #email = 'firstname.lastname#email.com/IMCLientName'
SELECT SUBSTRING(#email,0, CHARINDEX('#',#email))
Building on Ian Nelson's example we could add a quick check so we return the initial value if we don't find our index.
DECLARE #email VARCHAR(100)
SET #email = 'firstname.lastname.email.com/IMCLientName'
SELECT CASE WHEN CHARINDEX('#',#email) > 0
THEN SUBSTRING(#email,0, CHARINDEX('#',#email))
ELSE #email
END AS email
This would return 'firstname.lastname.email.com/IMCLientName'. If you used 'firstname.lastname#email.com/IMCLientName' then you would receive 'firstname.lastname' as a result.
Dear all,
I am using SQL Server 2008.
I am facing a scenario where I have to send mail to single or multiple user depending on the query. I tried this stmt to send mail to multiple recipients
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'imran' ,
#recipients= 'imran.khan#bbraun.com;amol.puranik#bbraun.com',
#subject = 'Test mail'
It succesfully sent mail.
Now I want to send mail depending on query. With single employee it is no issue, but if it is more then one employee how can I mail to multiple recipients.
That is my question is in this sp to send multiple recipients one has to separate addresses with ; . How can I arrange recipients so that the ; comes in between.
Thank you.
Unfortunately, you're not giving us a lot to go on - you don't show us the query to select your employees, you're not telling us anything about what the Employee table looks like, so all we can do is guessing - at best.
So here's my guess: you want to somehow select multiple employees, and their e-mail addresses should be concatenated together, separated by a semicolon (;), and then used for your sp_send_dbmail call.
One method to do this could be this:
DECLARE #recipients VARCHAR(4000)
SELECT
#recipients = STUFF((SELECT ';' + EMail
FROM dbo.Employees
WHERE (some condition here to find the right employees)
FOR XML PATH('')
), 1, 1, '')
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'imran',
#recipients,
#subject = 'Test mail'
Use a function like this -
CREATE FUNCTION coltocsv
(
--your input parameters
)
RETURNS nvarchar(3000)
AS
BEGIN
-- Declare the return variable here
declare #keywords nvarchar(3000)
--Build your csv string of keywords
Select #keywords = null
SELECT #Keywords = Coalesce(#Keywords + '; ', '') +
ColumnName
from Table
where <some condition>
--- Return the result of the function
RETURN #keywords
END
for the recipients, you can seggregate the miultiple email id's by [];
declare #ccmailid varchar(2000);
select #ccmailid = stuff((select '],['+ mailid from table_name
order by '],['+ mailid
for xml path('')),1,2,'')+']'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'imran' ,
#recipients= #ccmailid,
#subject = 'Test mail'