title: Why is this batch file not executing automatically?
body: <p>Basically I have a batch file which calls a SQL Server 2008 R2 stored procedure that interogates that DB for fragmentated tables over 5% fragmented and outputs the report to a text file.</p>
  
  <p>The batch file is set as a Task Scheduler job to run overnight.</p>
  
  <p>In Task Scheduler If I right click the task and select run immediately it executes fine, the script is in turn run on SQL Server and the output is redirected to a text file, everything is working as desired at this point, the problem is when I automate it to trigger overnight.</p>
  
  <pre><code>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%
  </code></pre>
  
  <p>The problem is that when left alone the Task Scheduler job will not run and the task says completed successfully with return code 255?</p>
  
  <p>The Task is set to run using the system administrator account.</p>
  
  <p>P.S. The Stored Procedure is:</p>
  
  <pre><code>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] &gt; @IndexFragmentationPercentage
  order by TableName
  END
  </code></pre>