我在SQL Server代理中通过sp_executesql
运行命令。如何从此命令捕获消息,以便将其记录在表中?
特别是我试图截断数据库日志,并希望能够看到这是否成功。我在代理SP中添加了代码片段:
IF (@truncate = 1)
BEGIN
SET @msg = 'Truncating log ''' + @description + ''' for the ''' + @db + ''' database'
EXEC _LogInsert 'Information', '_Loop', 'Status', @msg
--PRINT 'Attempting to truncate the log file'
SET @sql = N'USE [' + @db + ']' +
'DECLARE @LogFile varchar(128)' +
'SELECT TOP 1 @LogFile = [Name] ' +
'FROM sys.database_files ' +
'WHERE ([Type_Desc] = ''LOG'')' +
'DBCC SHRINKFILE(@LogFile, EMPTYFILE)' +
'DBCC SHRINKFILE(@LogFile, 10) WITH NO_INFOMSGS'
--PRINT 'truncation attempt finished'
EXEC sp_executesql @sql
-- Capture messages from SP
-- SET @msg = 'Truncating log msg ''' + @resmsg + ''' for the ''' + @db + ''' database'
-- EXEC _LogInsert 'Information', '_Loop', 'Status', @msg
END
答案 0 :(得分:0)
如果您将其作为工作运行,则可以从dbo.sysjobhistory获取所需数据(至少DBCC
输出或PRINT
):
SELECT jh.[run_date],
jh.[step_name],
jh.[message]
FROM msdb.dbo.sysjobhistory jh
INNER JOIN msdb.dbo.sysjobs j
ON j.[name] = 'job_name' and j.job_id = jh.job_id
另外,请注意WITH NO_INFOMSGS
- 这会抑制所有信息性消息。