私は基本的に次のことをしたいストアドプロシージャを持っています:
- 一時テーブルを作成し (存在しない場合)、データを入力します。
- クエリを 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」部分に関連していると思います。
ありがとう