Skip to content

Instantly share code, notes, and snippets.

Created December 18, 2015 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/ce32412ebfcae05ebc78 to your computer and use it in GitHub Desktop.
Save anonymous/ce32412ebfcae05ebc78 to your computer and use it in GitHub Desktop.
-- Create a new version of the table
CREATE TABLE dbo.Example2
(
SomeID integer NOT NULL,
StartDate date NOT NULL,
EndDate date NOT NULL
);
-- Add the appropriate clustered index
CREATE UNIQUE CLUSTERED INDEX CX_Example_SomeID_StartDate
ON dbo.Example2 (SomeID, StartDate)
WITH (MAXDOP = 1);
-- Copy the data into the new table, similar to the Manual Halloween Protection approach
INSERT INTO dbo.Example2 WITH (TABLOCK) (SomeID, StartDate, EndDate)
SELECT
E.SomeID,
E.StartDate,
ISNULL(DATEADD(DAY, -1,
LEAD(E.StartDate) OVER (
PARTITION BY E.SomeID
ORDER BY E.StartDate)), CONVERT(date, '99991231', 112)) AS EndDate
FROM dbo.Example AS E WITH (TABLOCK)
OPTION (MAXDOP 1);
-- Drop (or, alternatively rename out of the way, the old table)
DROP TABLE dbo.Example;
-- Rename the new table to take the place of the old table
EXEC sp_rename 'dbo.Example2', 'Example';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment