为什么这个批处理文件没有自动执行?

时间:2017-05-31 08:25:33

标签: batch-file stored-procedures sql-server-2008-r2 scheduled-tasks

基本上我有一个批处理文件,它调用一个SQL Server 2008 R2存储过程,该过程将该数据库与超过5%碎片化的分段表进行交互,并将报告输出到文本文件。

将批处理文件设置为任务计划程序作业,以便在一夜之间运行。

在任务计划程序中如果我右键单击任务并选择立即运行它执行正常,脚本依次在SQL Server上运行并且输出被重定向到文本文件,此时一切正常工作,问题是我自动将其触发过夜。

set local
REM Preparing Timestamp Information
set year=%date:~6,4%
set month=%date:~3,2%
set day=%date:~0,2%
set hour=%time:~0,2%
REM Replace leading space with zero
if “%hour:~0,1%” ==” ” set hour=0%hour:~1,1%
set minute=%time:~3,2%
set seconds=%time:~6,2%
set FILENAMEANDPATH= c:\DBMaintenanceLogs\SP_InspectorLog_%day%-%month%-%year%_%hour%-%minute%-%seconds%.log

sqlcmd -S .\SQLEXPRESS -E -Q "EXEC sp_DBIndexFragmentationInspector @IndexFragmentationPercentage=5" -d MyDBName -o %FILENAMEANDPATH%

问题是当单独使用时,任务计划程序作业将无法运行,并且任务说明已成功完成并返回代码为255?

任务设置为使用系统管理员帐户运行。

P.S。存储过程是:

USE [MyDBName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_DBIndexFragmentationInspector]
@IndexFragmentationPercentage INT
AS
BEGIN
SELECT
    OBJECT_NAME(A.[object_id]) as 'TableName',
    B.[name] as 'IndexName',
    A.[index_type_desc],
    A.[avg_fragmentation_in_percent]
FROM
    sys.dm_db_index_physical_stats(db_id(),NULL,NULL,NULL,'LIMITED') A
INNER JOIN
    sys.indexes B ON A.[object_id] = B.[object_id] and A.index_id = B.index_id 
where [avg_fragmentation_in_percent] > @IndexFragmentationPercentage
order by TableName
END

1 个答案:

答案 0 :(得分:0)

我遇到了完全相同的错误。对我来说,解决方案是在脚本末尾添加exit 0。我不明白为什么,但它有效。