Skip to content

Instantly share code, notes, and snippets.

@Wind010
Created April 8, 2023 02:47
Show Gist options
  • Select an option

  • Save Wind010/19cba51cea3710ce49385400b54ba388 to your computer and use it in GitHub Desktop.

Select an option

Save Wind010/19cba51cea3710ce49385400b54ba388 to your computer and use it in GitHub Desktop.
Run dynamic query over chunked/partitioned intervals.
DECLARE @start_date DATETIME = '2023-04-07 00:00:00'
DECLARE @end_date DATETIME = '2023-04-08 23:00:00'
DECLARE @hours CURSOR;
DECLARE @interval INT = 1;
-- You can adjust the to every n hour range if needed.
SET @hours = CURSOR FOR
WITH cte_hourly_timestamps AS (
SELECT CONVERT(datetimeoffset, @start_date) AS start_hour
UNION ALL
SELECT DATEADD(HOUR, @interval, start_hour)
FROM cte_hourly_timestamps
WHERE start_hour < CONVERT(datetimeoffset, @end_date)
),
cte_range_timestamps AS (
SELECT start_hour, DATEADD(HOUR, @interval, start_hour) as end_hour FROM cte_hourly_timestamps
)
SELECT * FROM cte_range_timestamps
DECLARE @sql VARCHAR(1000)
OPEN @hours
FETCH NEXT from @hours INTO @start_date, @end_date
WHILE @@fetch_status = 0
BEGIN
--PRINT CONVERT(VARCHAR, @start_date, 120)
--PRINT CONVERT(VARCHAR, @end_date, 120)
-- Update below query to whatever suites your needs
SET @sql = 'SELECT TOP(100) *
FROM [dbo].[Events] WITH (NOLOCK)
WHERE CreateDate BETWEEN ''' + CONVERT(VARCHAR, @start_date, 120) + ''' AND ''' + CONVERT(VARCHAR, @end_date, 120) + '''
AND EventType = ''Approval''
AND JSON_VALUE(EventObject, ''$.Items[0].Nested.Code'') IS NULL'
--PRINT @sql
-- Comment below for testing.
EXEC (@sql)
--BREAK;
FETCH NEXT FROM @hours INTO @start_date, @end_date
END
CLOSE @hours
DEALLOCATE @hours
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment