我有一个存储过程,基本上我想做以下事情:
- 创建临时表(如果不存在)并填充数据
- 将查询输出到 SSMS,并为查询分配一个变量 (@sql)
- 使用查询,将查询的内容通过电子邮件发送给收件人
我的脚本是这样的:
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”部分有关。
谢谢