Microsoft SQL Server 2005 Best Practices

How to find missing values in a date sequence using EXCEPT?

 

Execute the following script in Query Editor to find missing order dates:

USE AdventureWorks;

DECLARE @MaxOrderDate char(8), @MinOrderDate char(8), @RunningDate char(8)
DECLARE @AllDates table (Date char(8))

SELECT @MaxOrderDate = convert(char(8),max(OrderDate),112),
@MinOrderDate=convert(char(8),min(OrderDate),112)
FROM Sales.SalesOrderHeader

SET @RunningDate = @MinOrderDate
WHILE (@RunningDate <= @MaxOrderDate )
BEGIN
INSERT @AllDates SELECT @RunningDate
SET @RunningDate = convert(char(8),dateadd(day, 1, @RunningDate),112)
END

SELECT Date FROM @AllDates
EXCEPT
SELECT DISTINCT convert(char(8),OrderDate,112)
FROM Sales.SalesOrderHeader


GO


 

The Best SQL Server 2005 Training in the World
 
 
SQLUSA.com Home Page