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

时间:2018-11-20 21:19:25

标签: sql-server-2017 sp-send-dbmail drop-table ssms-2017

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

  1. 创建临时表(如果不存在)并填充数据
  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 ;

我第一次收到以下消息:

  

第208条消息,第16级,状态0,过程dbo.ListDaysofYear,第25行
  [Batch Start Line 52]无效的对象名称'## daysofYear

我相信它与T-SQL的“ DROP TABLE”部分有关。

谢谢

1 个答案:

答案 0 :(得分:1)

认为我发现了问题:

IF OBJECT_ID('tempdb.dbo.##daysofYear','U') IS NOT NULL <-在这里,如果存在的话,您将删除该表,但是没有创建它,因此它在第25行中尝试插入数据(到您放置的表)时引发错误。我建议用TRUNCATE TABLE替换drop table。