问题
I frequently use the msdb.dbo.sp_send_dbmail
tool in SQL Server for automated reports and such but I've never really used it to for an update/delete type statement in the @query
section.
Is it possible to do so? When I run this query, it gives 0 results and doesn't execute the actual Merge and Delete function within the @query
section.
I'm running a test scenario where I know there should be results, and that it should be deleted but no dice. Any advice appreciated as I may be missing something as I'm thinking it might be an order issue. But I thought putting it within the @query
should execute as should be. Query style below:
DECLARE @results NVARCHAR(1000)
Select @results = N'
MERGE Table1 A
USING Table2 B
ON A.ID = B.ID and A.recorddate = B.recorddate
WHEN NOT MATCHED BY SOURCE THEN delete
OUTPUT
$action,
deleted.*;';
Begin
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Test',
@recipients= 'test@test.com',
@query = @results,
@from_address = 'test@test.com',
@subject ='Delete Row',
@attach_query_result_as_file = 1,
@query_attachment_filename = 'Merge Test',
@query_result_separator='$',
@query_result_width =32767,
@query_result_no_padding=1,
@body = 'Results',
@body_format = 'HTML' ;
End
The result of the query should execute and delete the unneeded row and then output the results which I'm hoping could be exported to the .CSV
and e-mailed to me so I can review what was deleted.
EDIT: Got it! Just going to use a temporary table to store results and dump that into a .csv and drop it at the end
select * into #temptable from TableA where 0=1;
MERGE Table1 A
USING Table2 B
ON A.ID = B.ID and A.recorddate = B.recorddate
WHEN NOT MATCHED BY SOURCE THEN delete
OUTPUT
$action,
deleted.* INTO #temptable;
drop table #temptable
来源:https://stackoverflow.com/questions/61549479/use-the-merge-output-function-to-dump-results-with-msdb-dbo-sp-send-dbmail