Search code examples
sql-servert-sqlsp-send-dbmail

send multiple emails from a table using send dbmail stored proc in sql


I am trying to send multiple emails from my table using sp_send_dbmail but i am getting this error when i run the stored procedure. Here is the error i am getting:

Parameter @attach_query_result_as_file cannot be 1 (true) when no value is specified for parameter @query. A query must be specified to attach the results of the query.

here is my code

  SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER proc [dbo].[myProc] as   
    declare rscursor cursor read_only
    for 
     select Email, FullName from myTable
      where userActive =1

        declare @Emails            nvarchar (100)
        declare @FullName  nvarchar (100)


    open rscursor
    fetch next from rscursor into @Emails, @FullName

    while @@fetch_status=0
        begin

             EXEC msdb.dbo.sp_send_dbmail
            @recipients = @Emails, 
            @subject = 'Sleep Diary Reminder',

            @body = 'this is just test',
            @profile_name = 'myProfile',


            @attach_query_result_as_file = 1        

        fetch next from rscursor into @Emails, @FullName

    end
    close rscursor
    deallocate rscursor

running my sp

EXEC dbo.myProc

Solution

  • Since you're not attaching a query to the mail using the @query variable for the procedure sp_send_dbmail either set @attach_query_result_as_file = 0 or remove the variable altogether. Or attach a query if that is what you want to do - you could try to add @query = 'SELECT GETDATE()' to see that it works.