简体   繁体   中英

How to send email to multiple recipients when new row inserted ?

I'm using SQL Server 2014

I have a table A with these columns:

planNo, parcelNo, id

And another table B with these columns:

planNo, parcelNo, userEmail

When a new row is inserted into table A , I want to send an email to userEmail for all rows in table B that has the same parcelNo and planNo

This is too long for a comment.

You know the answer, because you have tagged the question "trigger". Are you asking other people to write your code for you, when you haven't even tried to write it? You should attempt yourself.

In my opinion, sending emails through triggers is dangerous. I much prefer an API based approach that uses stored procedures. Mistakes in triggers can cause the database to lock.

Instead of inserting a row directly into the table and having a database trigger do the email, call a stored procedure to insert a row in A and then send the email in the stored procedure. So, the stored procedure would look something like this:

create procedure usp_InsertAndEmail (
    @planNo ??,
    @parcelNo ??,
    @id
) as
begin
    declare @email varchar(255);

    insert into a(planNo, parcelNo, id)
        values (@planNo, @parcelNo, @id);

    declare cursor b_cursor for
        select email
        from table b
        where b.planNo = @planNo and b.parcelNo = @parcelNo;

    open cursor b_cursor;

    fetch next from b_cursor into @email;

    while (@@fetch_status = 0)
    begin
        -- do email send however you do it
        fetch next from b_cursor into @email;
    end;
    close b_cursor;
    deallocate b_cursor;
end;

This approach also allows you to check for errors on the emailing.

I guess you use PHP?

    $requete= 'SELECT * FROM B WHERE planNo=\'.$plannumber.\' AND parcelNo=\'.$parcelnumber.\'';
$result = $bdd->query($requete);
    if($result)
                {
                    while ($donnees = $result->fetch())
                    {
                        $email=$donnees['userEmail'];
                        $header='From: Name Surname <your_email>'."\r\n";
                        $title='title of your mail';
                        $message='your message';
                        mail($email, $title, $message, $header);
                    }
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM