0

我有一个存储过程,基本上我想做以下事情:

  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 行
[批处理开始第 52 行] 无效的对象名称 '##daysofYear

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

谢谢

4

1 回答 1

1

认为我发现了问题:

IF OBJECT_ID('tempdb.dbo.##daysofYear','U') IS NOT NULL<-- 如果存在,您将删除该表,但不创建它,因此它会在第 25 行抛出错误,该行尝试插入数据(到您删除的表)。我建议用 TRUNCATE TABLE 替换 drop table。

于 2018-11-21T01:12:51.197 回答