SQL Server 2017 - 数据库邮件存储过程

SQL Server 2017 - Database mail stored procedure

我有一个存储过程,基本上我想执行以下操作:

  1. 创建临时文件 table(如果不存在)并填充数据
  2. 将查询输出到SSMS,并为查询分配一个变量(@sql)
  3. 使用查询,将查询内容通过电子邮件发送给收件人

我的脚本是这样的:

Create Procedure ListDaysofYear(@year as integer)
as 
    Declare @sql as varchar(200), @DBqry as varchar(200),
            @tab as char(1) = char(9)
    Declare @dayofyear as bigint = 1
    Declare @monthofyear as int = 1
    Declare @day as int = 1
    Declare @curDate as datetime
    Declare @DB as varchar(40)
    Declare @sql2 as varchar(40)

    Set @curDate = datefromparts(@year, @monthofyear, @day)
    Set @DB = 'msdb'

    IF OBJECT_ID('tempdb.dbo.##daysofYear','U') IS NOT NULL
        DROP TABLE ##daysofYear
        --Print 'YES'
    ELSE
        CREATE TABLE ##daysofYear
        (
             cDate DATETIME PRIMARY KEY NOT NULL,
             cMonth VARCHAR(20) NOT NULL,
             cDay VARCHAR(20) NOT NULL
        )

    WHILE year(@curDate) = @year
    BEGIN
        -- Insert rows based on each day of the year
        INSERT INTO ##daysofYear (cDate, cMonth, cDay)
        VALUES( (@curDate),
                (DATENAME([MONTH], @curDate)),
                (DATENAME([WEEKDAY], @curDate)) )

        SET @curDate = @curDate + 1
    END 

    --Output file to SSMS query window
    Select dy.* from ##daysofYear dy;

    Set @sql = 'Select dy.* from ##daysofYear dy;'
    Set @sql2 = 'Use ' + @DB + '; Exec msdb.dbo.sp_send_dbmail
             @profile_name = ''Notifications'',
             @recipients = ''mikemirabelli6@hotmail.com'',
             @attach_query_result_as_file = 1,
             @query_attachment_filename = ''daysofyear.txt'',
             @query_result_separator = '',
             @body = ''The attached output file - DaysofYear table'',
             @query = ''Select dy.* from ##daysofYear dy'' ;'

    --Execute sp_sqlexec @sql
    Exec(@sql2)

基本上当我运行执行行:

Exec dbo.ListDaysofYear 2018 ;

我第一次收到以下消息:

Msg 208, Level 16, State 0, Procedure dbo.ListDaysofYear, Line 25
[Batch Start Line 52] Invalid object name '##daysofYear

我认为这与 T-SQL 的 "DROP TABLE" 部分有关。

谢谢

我觉得我发现了问题:

IF OBJECT_ID('tempdb.dbo.##daysofYear','U') IS NOT NULL <-- 在这里你删除了 table if exist 但没有创建它所以它在第 25 行抛出一个错误,它试图插入数据(到 table 你放弃了)。我建议将 drop table 替换为 TRUNCATE TABLE.