Skip to content

Instantly share code, notes, and snippets.

@jwoschitz
Created August 13, 2011 08:12
Show Gist options
  • Save jwoschitz/1143601 to your computer and use it in GitHub Desktop.
Save jwoschitz/1143601 to your computer and use it in GitHub Desktop.
Create multiple batch statements with a delay in between each batch execution / T-SQL
/*
Creates multiple batch statements to run a sql statement with a delay in between each batch execution.
*/
DECLARE
@ReportTimeStamp DATETIME,
@ExitConditionTimeStamp DATETIME,
@Sql NVARCHAR(MAX),
@ParamsDefinition NVARCHAR(MAX),
@IntervalInSeconds INT,
@DelayInSeconds INT
SET @ReportTimeStamp = '20110701'
SET @ExitConditionTimeStamp = '20110731'
SET @IntervalInSeconds = 24 * 60 * 60
SET @Sql = 'EXEC YourDatabase.dbo.YourProcedure @ReportDate'
SET @ParamsDefinition = '@ReportDate DATETIME'
SET @DelayInSeconds = 30
WHILE @ReportTimeStamp <= @ExitConditionTimeStamp
BEGIN
PRINT 'BEGIN
WAITFOR DELAY ''' + CONVERT(NVARCHAR(8),DATEADD(S,@DelayInSeconds, '19000101'),108) + '''
EXEC sp_executesql N''' + @Sql + ''', N''' + @ParamsDefinition + ''', @ReportDate = ''' + CONVERT(NVARCHAR(8),@ReportTimeStamp,112) + '''
PRINT ''Query executed:''+CAST(GETDATE() AS CHAR)
END;
GO'
SET @ReportTimeStamp = DATEADD(S,@IntervalInSeconds,@ReportTimeStamp)
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment