Home Forums SQL Server 2008 T-SQL (SS2K8) Loop Through the records - send email - set the value of the field - Need Code Help RE: Loop Through the records - send email - set the value of the field - Need Code Help

  • here's an example of what you are asking;

    you'll have to use a cursor if you want to send emails on a per-email basis from the data.

    remember that when you assign parameters, you cannot concatent/use functions/manipulate anything in the assignment, that has to occur BEFORE you assign it.

    --so this is bad:

    EXEC msdb.dbo.sp_send_dbmail

    @subject = 'Please send Feedback for Order#' + Orders.OrderNum

    --this is the correct way:

    declare @var varchar(128)

    SET @var ='Please send Feedback for Order#' + Orders.OrderNum

    EXEC msdb.dbo.sp_send_dbmail

    @subject =@var

    and here's the full exmaple:

    DECLARE

    @isql VARCHAR(2000),

    @email VARCHAR(64),

    @order VARCHAR(64),

    @emailSubject varchar(128),

    @emailBody varchar(128)

    DECLARE c1 CURSOR FOR

    SELECT

    CustomerEmailAddress,

    OrderNum

    FROM Orders

    WHERE EmailSent = 0

    OPEN c1

    FETCH NEXT FROM c1 INTO @email,@order

    WHILE @@FETCH_STATUS <> -1

    BEGIN

    SELECT

    @emailSubject = 'Please send Feedback for Order#' + @order,

    @emailBody = @emailSubject --you'd build a bigger, more descriptive string for the body.

    --you cannot concatenate strings as the parameters for a query, they must be eitehr a static string or an already built variable.

    EXEC msdb.dbo.sp_send_dbmail

    @profile_Name ='Administrator',

    @recipients= @email ,

    @subject = @emailSubject,

    @body = @emailBody

    FETCH NEXT FROM c1 INTO @email,@order

    END

    CLOSE c1

    DEALLOCATE c1

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!