使用 sql 中的 send dbmail 存储过程从 table 发送多封电子邮件

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

我正在尝试使用 sp_send_dbmail 从我的 table 发送多封电子邮件,但是当我 运行 存储过程时出现此错误。这是我收到的错误:

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.

这是我的代码

  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

运行我的 sp

EXEC dbo.myProc

由于您没有使用 @query 变量为过程 sp_send_dbmail 将查询附加到邮件,因此请设置 @attach_query_result_as_file = 0 或完全删除该变量。或者附加一个查询,如果这是你想要做的 - 你可以尝试添加 @query = 'SELECT GETDATE()' 看看它是否有效。