We have a couple million rows of data that we need to "explode" out by adding a row for every date between the started_at date and the ended_at date. The while loop is what is taking the longest in our query.
Any idea on how to optimize or replace it?
IF (OBJECT_ID('TempDb..#exploded_services') IS NOT NULL)
DROP TABLE #exploded_services;
CREATE TABLE #exploded_services
(
target_date date,
move_id varchar(30),
initiation_id varchar(30),
initiated_at date,
booked_at date,
transferee varchar(60),
account_id varchar(30),
mc_id varchar(30),
po varchar(60),
weight int,
service varchar(150),
started_at date,
ended_at date,
location_id nvarchar(64),
description varchar(max),
provider varchar(max),
mode varchar(60),
origin_location_id nvarchar(64),
destination_location_id nvarchar(64),
transferee_phone varchar(40),
transferee_email varchar(100),
status varchar(10),
ordinal int
);
WHILE (@pointer <= @end_date)
BEGIN
INSERT INTO #exploded_services
SELECT
@pointer,
svcs.*
FROM #Services svcs
WHERE @pointer BETWEEN svcs.started_at AND COALESCE(svcs.ended_at,@end_date)
SET @pointer = DATEADD(dd, 1, @pointer)
END;
dd. Not much more effort to typeday, but it sure is more readable (never mind reliable).